PHP - Session_start
i keep getting this error whenever i load my page
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\xampp\htdocs\wiki\index.php:1) in C:\xampp\htdocs\wiki\index.php on line 2 <?php session_start(); include "includes/dbconnect.php"; include "includes/functions.php"; forum_connect(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <link rel="stylesheet" type="text/css" href="../style.css" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Wiki</title></head> <body id="page1"> <div id="header"> <div class="container"> <div class="logo"> <a href="index.html"><img src="images/logo.gif" alt="logo" /></a> </div> i've made sure that session_start() is at the very top, and there are no rogue spaces or breaks , so i dont know why i'm getting the error. any ideas? thanks Similar TutorialsThe php web video script that I’m using displays a User’s profile page, by simply adding (for example) …/@UserName after the url into a browser. I tried to have a User’s profile page only display to Users who are logged into the site, by adding session code: if(!isset($_SESSION['username'])){ header("Location:../login"); exit(); } like so: <?php if(!isset($_SESSION['username'])){ header("Location:../login"); exit(); } if (empty($_GET['id'])) { header("Location: " . PT_Link('')); exit(); } $username = PT_Secure($_GET['id']); $user_id = $db->where('username', $username)->getOne(T_USERS); $lists = false; if (empty($user_id)) { header("Location: " . PT_Link('')); exit(); } $pt->page_url_ = $pt->config->site_url.'/@'.$username ; $pt->second_page = 'videos'; if (!empty($_GET['page'])) { switch ($_GET['page']) { case 'liked-videos': $pt->second_page = 'liked-videos'; break; case 'about': $pt->second_page = 'about'; break; case 'play-lists': $pt->second_page = 'play-lists'; $lists = true; break; } $pt->page_url_ = $pt->config->site_url.'/@'.$username."?page=".$pt->second_page; } $user_data = PT_UserData($user_id, array( 'data' => true )); etc...
but was unsuccessful. The problem is although the …/@UserName no longer displays in the browser field (and redirects to the login page) (with that additional code), once logged in, the User can’t see his Profile Page either. if(!isset($_SESSION['username'])){ header("Location:../login"); print_r($_SESSION); exit; } but I see no printed results. I have tried this: <?php session_start(); if(!isset($_SESSION['username'])){ header("Location:../login"); exit(); } but, when I select the drop-down menu > profile, it just seems to refresh the same page (that I'm on, and doesn't take me to the ../@chrisj profile page, as it did before I added this: if(!isset($_SESSION['username'])){ header("Location:../login"); exit(); } Also, the .htaccess file shows this: RewriteRule ^@([^\/]+)(\/|)$ index.php?link1=timeline&id=$1 [QSA] if that is any clue.
I went ahead and asked the developer, and he simply said:
just FYI -When a user logs in it sets the $_SESSION[‘username’] variable, id, etc.) if(!isset($_SESSION['username'])){ header("Location:../login"); So, is there a solution that might instruct to say something like 'if already logged in go to @ the username’s profile page? something like: if (IS_LOGGED == true) { any additional suggestions are welcomed
For as long as I can remember, I always start my php scripts with...
// Initialize session. session_start();
On my webserver, cPanel keeps populating a error_log with the following entry..
[<date>] PHP Notice: session_start(): session has already been started - ignoring in path/to/suspect/script.php on line 10
Have I been using PHP session incorrectly all of this time?! Fwiw, I don't get this error - at least not that I know - locally in MAMP...
I have a login script that sets all my $_SESSION[] variables, it was working, now I'm redesigning, and now its not working. I can echo the variables on this page, but when it redirects to dashboard.php and I do a session_start(), nothing. It's driving me nuts. <?php require_once ('../includes/config.php'); require_once ('../includes/connect.php'); function clean($str) { $str = @trim($str); if(get_magic_quotes_gpc()) { $str = stripslashes($str); } return mysql_real_escape_string($str); } //Sanitize the POST values $login = clean($_POST['login']); $password = clean($_POST['password']); //Input Validations if($login == '') { $errmsg_arr[] = 'Login ID missing'; $errflag = true; } if($password == '') { $errmsg_arr[] = 'Password missing'; $errflag = true; } //If there are input validations, redirect back to the login form if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; session_write_close(); header("location: ../../index.html"); exit(); } //Create query $qry="SELECT * FROM members WHERE login='$login' AND passwd='".md5($_POST['password'])."'"; $result=mysql_query($qry); //Check whether the query was successful or not if($result) { if(mysql_num_rows($result) == 1) { //Login Successful session_regenerate_id(); $member = mysql_fetch_assoc($result); $_SESSION['MEMBERID'] = $member['member_id']; $_SESSION['AGENTNAME'] = $member['firstname'] . " " . $member['lastname']; $_SESSION['OFFICE'] = $member['office']; $_SESSION['AGENCY'] = $member['agency']; $_SESSION['LOGIN'] = $member['login']; $_SESSION['EMAIL'] = $member['email']; $_SESSION['USERLEVEL'] = $member['level']; $_SESSION['EMPID']= $member['empid']; $_SESSION['LICENSE'] = $member['license']; session_write_close(); header("location: ../dashboard.php"); exit(); }else { //Login failed header("location: ../../index.html"); exit(); } }else { die("Query failed"); } ?> My code seems to be working correctly however I get the following error Code: [Select] Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/party/public_html/en/header.php:12) in /home/party/public_html/en/requests.php on line 36 is there a way to fix this message or keep it from displaying the code is below form: <img src="captcha/index.php" width="120" height="30" border="1" alt="CAPTCHA"></p> <p><input type="text" size="6" maxlength="5" name="captcha" value=""><br> <small>copy the digits from the image into this box</small></p> captcha/index.php <?PHP // Adapted for The Art of Web: www.the-art-of-web.com // Based on PHP code from: php.webmaster-kit.com // Please acknowledge use of this code by including this header. // initialise image with dimensions of 120 x 30 pixels $image = @imagecreatetruecolor(120, 30) or die("Cannot Initialize new GD image stream"); // set background and allocate drawing colours $background = imagecolorallocate($image, 0x66, 0x99, 0x66); imagefill($image, 0, 0, $background); $linecolor = imagecolorallocate($image, 0x99, 0xCC, 0x99); $textcolor1 = imagecolorallocate($image, 0x00, 0x00, 0x00); $textcolor2 = imagecolorallocate($image, 0xFF, 0xFF, 0xFF); // draw random lines on canvas for($i=0; $i < 6; $i++) { imagesetthickness($image, rand(1,3)); imageline($image, 0, rand(0,30), 120, rand(0,30) , $linecolor); } session_name("captcha"); session_start(); // add random digits to canvas using random black/white colour $digit = ''; for($x = 15; $x <= 95; $x += 20) { $textcolor = (rand() % 2) ? $textcolor1 : $textcolor2; $digit .= ($num = rand(0, 9)); imagechar($image, rand(3, 5), $x, rand(2, 14), $num, $textcolor); } // record digits in session variable $_SESSION['digit'] = $digit; // display image and clean up header('Content-type: image/png'); imagepng($image); imagedestroy($image); ?> after form is submitted: session_start(); if($_POST['captcha'] != $_SESSION['digit']) { echo "<p><b>--Sorry, the CAPTCHA code entered was incorrect!--</b><p>"; } else { $query = "INSERT INTO rp_request (name, type, request, ipaddr, time) VALUES('$name','$type','$request','$ipaddr','$time')"; mysql_query($query) or die(mysql_error()); echo "<p><b>--Your Request Has Been Sent--</b><p>";} session_destroy(); In the PHP manual, under session_start(), it says: Quote To use cookie-based sessions, session_start() must be called before outputting anything to the browser. Does this mean I cannot place it in the middle of a HTML file? What about if I put it on line 1 of a HTML document (before the DOCTYPE! (HTML 4.01))? Hi im getting the following error message in my admin area: Code: [Select] Warning: session_start() [function.session-start]: open(/home/users/web/b109/ipg.removalspacecom/cgi-bin/tmp/sess_9b495d20f1a5e1cb9eaed99c1b5dfed6, O_RDWR) failed: No such file or directory (2) in /hermes/bosweb25a/b109/ipg.removalspacecom/admin01.php on line 2 Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /hermes/bosweb25a/b109/ipg.removalspacecom/admin01.php:2) in /hermes/bosweb25a/b109/ipg.removalspacecom/admin01.php on line 2 Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /hermes/bosweb25a/b109/ipg.removalspacecom/admin01.php:2) in /hermes/bosweb25a/b109/ipg.removalspacecom/admin01.php on line 2 There are 1 removalspace users so far. Company Name Contact Name Contact Number Email Address Line 1 Address Line 2 Location Postcode Basic Members Upgraded Users Company Logo Approved none none none andy_b_1502@hotmail.co.uk none none none none Current level = 0 Level 1 - Free Level 2 - Basic Level 3 - Premium Level 0 - Do Not Display Warning: Unknown: open(/home/users/web/b109/ipg.removalspacecom/cgi-bin/tmp/sess_9b495d20f1a5e1cb9eaed99c1b5dfed6, O_RDWR) failed: No such file or directory (2) in Unknown on line 0 Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/home/users/web/b109/ipg.removalspacecom/cgi-bin/tmp) in Unknown on line 0 Admin01.php Code: [Select] <?PHP session_start(); /* really need to use a session variable to insure authorized to be here */ include ('db.php'); /* ======================================== 99% of the time it is better to put your query in a string. It makes debugging much easier ======================================== */ $query = "SELECT * FROM companies"; $result = mysql_query($query ) or die("SELECT Error: ".mysql_error()); $num_rows = mysql_num_rows($result); /* ======================================== I find it easier to locate problems if I indent code properly and drop out of PHP if there are large sections of html ======================================== */ ?> <br><br><br>There are <?PHP echo $num_rows; ?> removalspace users so far.<P> <table width="819" height="114"> <tr> <th>Company Name</th> <th>Contact Name</th> <th>Contact Number</th> <th>Email</th> <th>Address Line 1</th> <th>Address Line 2</th> <th>Location</th> <th>Postcode</th> <th>Basic Members</th> <th>Upgraded Users</th> <th>Company Logo</th> <th>Approved</th> </tr> <tr> <td colspan="6"></td> </tr> <?PHP while ( $row = mysql_fetch_array($result, MYSQL_ASSOC )) { ?> <tr> <td><?PHP echo $row['company_name']; ?></td> <td><?PHP echo $row['contact_name']; ?></td> <td><?PHP echo $row['phone']; ?></td> <td><?PHP echo $row['email']; ?></td> <td><?PHP echo $row['street1']; ?></td> <td><?PHP echo $row['street2']; ?></td> <td><?PHP echo $row['location']; ?></td> <td><?PHP echo $row['postcode']; ?></td> <td><?PHP echo $row['basicpackage_description']; ?></td> <td><?PHP echo $row['premiumuser_description']; ?></td> <?PHP /* ======================================== I presume you want to show the thumb version here ======================================== */ ?> <td><img src="images/thumbs/<?PHP echo $row['upload']; ?>" alt="logo"/></td> </tr> <tr> <td colspan="10"> <table> <tr> <td>Current level = <?PHP echo $row['approved']; ?></td> <td><a href="admin02.php?id=<?PHP echo $row['id']; ?>&level=1">Level 1 - Free</a></td> <td><a href="admin02.php?id=<?PHP echo $row['id']; ?>&level=2">Level 2 - Basic</a></td> <td><a href="admin02.php?id=<?PHP echo $row['id']; ?>&level=3">Level 3 - Premium</a></td> <td><a href="admin02.php?id=<?PHP echo $row['id']; ?>&level=0">Level 0 - Do Not Display</a></td> </tr> </table> </tr> <?PHP } echo "</table>"; ?></table> Then when i click to change something e.g level of user, i get this error message: Code: [Select] Warning: session_start() [function.session-start]: open(/home/users/web/b109/ipg.removalspacecom/cgi-bin/tmp/sess_d986479c3603a52a37390b24a12caf03, O_RDWR) failed: No such file or directory (2) in /hermes/bosweb25a/b109/ipg.removalspacecom/admin02.php on line 2 Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /hermes/bosweb25a/b109/ipg.removalspacecom/admin02.php:2) in /hermes/bosweb25a/b109/ipg.removalspacecom/admin02.php on line 2 Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /hermes/bosweb25a/b109/ipg.removalspacecom/admin02.php:2) in /hermes/bosweb25a/b109/ipg.removalspacecom/admin02.php on line 2 Warning: Cannot modify header information - headers already sent by (output started at /hermes/bosweb25a/b109/ipg.removalspacecom/admin02.php:2) in /hermes/bosweb25a/b109/ipg.removalspacecom/admin02.php on line 9 Warning: Unknown: open(/home/users/web/b109/ipg.removalspacecom/cgi-bin/tmp/sess_d986479c3603a52a37390b24a12caf03, O_RDWR) failed: No such file or directory (2) in Unknown on line 0 Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/home/users/web/b109/ipg.removalspacecom/cgi-bin/tmp) in Unknown on line 0 Admin02.php Code: [Select] <?PHP session_start(); /* really need to use a session variable to insure authorized to be here */ include('db.php'); $id = (int) $_GET['id']; $level = (int) $_GET['level']; $query = "UPDATE companies set approved = '$level' WHERE id = '$id'"; $result = mysql_query($query); header("Location: admin01.php"); ?> Can someone please help with this please? Hi guys, (I'm not sure if this is in the right topic. If not please could you move to the correct topic thanks.) Ok I recently moved my website from the host ULMB to a new host called Awardspace. My web site is a PHP code MMORPG which uses a MYSQL database. Whilst moving the website I did not change any of the PHP code. On the new host the PHP code still does work as it was programmed to do but these errors keep occurring on all the pages which contain PHP code to update the MYSQL database: Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /~/www/europeanwarfare.atwebpages.com/checklogin.php:1) in /srv/disk4/657046/www/europeanwarfare.atwebpages.com/connection2.php on line 2 Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /~/www/europeanwarfare.atwebpages.com/Shop/R3.php:1) in /~/www/europeanwarfare.atwebpages.com/Shop/R3.php on line 32 Warning: mysql_query() [function.mysql-query]: Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) in /~/www/europeanwarfare.atwebpages.com/Shop/R3.php on line 124 Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /~/www/europeanwarfare.atwebpages.com/Shop/R3.php on line 124 Warning: mysql_select_db(): 2 is not a valid MySQL-Link resource in /~/www/europeanwarfare.atwebpages.com/Shop/R3.php on line 126 Warning: mysql_query() [function.mysql-query]: Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) in /~/www/europeanwarfare.atwebpages.com/Shop/R3.php on line 127 Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /~/www/europeanwarfare.atwebpages.com/Shop/R3.php on line 127 Warning: mysql_close(): 2 is not a valid MySQL-Link resource in /~/www/europeanwarfare.atwebpages.com/Shop/R3.php on line 128 Warning: mysql_select_db(): 2 is not a valid MySQL-Link resource in /~/www/europeanwarfare.atwebpages.com/Shop/R3.php on line 129 Warning: mysql_query() [function.mysql-query]: Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) in /~/www/europeanwarfare.atwebpages.com/Shop/R3.php on line 130 Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /~/www/europeanwarfare.atwebpages.com/Shop/R3.php on line 130 Warning: mysql_close(): 2 is not a valid MySQL-Link resource in /~/www/europeanwarfare.atwebpages.com/Shop/R3.php on line 131 Warning: mysql_select_db(): 2 is not a valid MySQL-Link resource in /~/www/europeanwarfare.atwebpages.com/Shop/R3.php on line 132 Warning: mysql_query() [function.mysql-query]: Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) in /~/www/europeanwarfare.atwebpages.com/Shop/R3.php on line 133 Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /~/www/europeanwarfare.atwebpages.com/Shop/R3.php on line 133 Warning: mysql_close(): 2 is not a valid MySQL-Link resource in /~/www/europeanwarfare.atwebpages.com/Shop/R3.php on line 134 I just don't understand why I keep getting these errors? The PHP code still works fine and does update and retrieve information from the MYSQL data base correctly but these error keep occurring I just don't understand it? I spock to Awardspace and found that they run PHP v5.2.5 and MYSQL v5.1 and my old host ULMB ran on PHP v5.3.3 and MYSQL v5.0.90. I don't know if this is what is causing the problem? Feel free to see the errors for your self go to the web site at http://europeanwarfare.atwebpages.com/ and use the user name: tester and password: tester to login and see the errors. Then go to any page which contains PHP update code and these will be a error but the code will still work correctly? Thanks For Any Help! Fraser Hi I have an addon Domain, so you can open the site like http://www.mydomain.com/folder/ or http://www.otherdomain.com Now I want that when you are logged in you will be logged in in both, they have both the same folder. The loggin process works with $_SESSION, is there a way that the session_start() and the session_destroy can handle both sites? First want to start by saying these pages work perfect on my own hosted devel server running centos5. I am moving these to godaddy for production and am running into this error: Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/content/93/6413093/html/classifieds/login.php:7) in /home/content/93/6413093/html/classifieds/init.php on line 2 The first page you browse to is index.php: <? header('location: secured_page.php'); ?> Header refers it to secured_page.php: <? require('init.php'); ?> Then there is a bunch of HTML code under neath this page. This is the secured (password protected) page. The init.php that is required: <? session_start(); require('config.php'); require('quotes.php'); With more PHP code under neath. The first 7 lines of the login.php page are all HTML code. The 7th line in this page that is PHP is: : sha1(sha1($_REQUEST['password']).$_SESSION['salt']); I cannot for the life of me figure out why this is happening. Checked for whitespace and characters before the session_start() in the init.php file. Any and all help is greatly appreciated. thanks -beemer My session start is in my session object and I include it at the top of my page prior my html code, yet I still get this warning: Code: [Select] Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /Users/Sites/writepaps/index.php:2) in /Users/Sites/writepaps/includes/functions/sessions.php on line 11 I include the object in index line 2. and line 11 is where my session start is in my construct function <?php require_once("database.php"); require_once("user.php"); class Sessions { public $logged_in = false; protected $username; protected $password; function __construct(){ session_start(); $this->check_login(); } .... Why is this happening? Im trying to create two chained select fields using a guide I found online. The page loads fine my error does not occur until I select the first option in the preloaded select box. When I do that I get the following error: Quote Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /Applications/XAMPP/xamppfiles/htdocs/include/session.php:480) in /Applications/XAMPP/xamppfiles/htdocs/include/session.php on line 46 I have never had this kind of issue before so Im clueless as to why its happening. Ill post the two involved files below (index.php,sessiong.php): index.php: Code: [Select] <?php include ("../include/session.php"); ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Chained Select Boxes using PHP, MySQL and jQuery</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#wait_1').hide(); $('#drop_1').change(function(){ $('#wait_1').show(); $('#result_1').hide(); $.get("../include/session.php", { func: "drop_1", drop_var: $('#drop_1').val() }, function(response){ $('#result_1').fadeOut(); setTimeout("finishAjax('result_1', '"+escape(response)+"')", 400); }); return false; }); }); function finishAjax(id, response) { $('#wait_1').hide(); $('#'+id).html(unescape(response)); $('#'+id).fadeIn(); } </script> </head> <body> <p> <form action="" method="post"> <select name="drop_1" id="drop_1"> <option value="" selected="selected" disabled="disabled">Select a Program</option> <?php getTierOne(); ?> </select> <span id="wait_1" style="display: none;"> <img alt="Please Wait" src="ajax-loader.gif"/> </span> <span id="result_1" style="display: none;"></span> </form> </p> <p> <?php if(isset($_POST['submit'])){ $drop = $_POST['drop_1']; $tier_two = $_POST['tier_two']; echo "You selected "; echo $drop." & ".$tier_two; } ?> <p><a href="three-tier/">View 3 Tier Select Box Example</a></p> </body> </html> Session.php: Code: [Select] <? /** * Session.php * * The Session class is meant to simplify the task of keeping * track of logged in users and also guests. * * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC) * Last Updated: August 19, 2004 */ include("database.php"); include("mailer.php"); include("form.php"); class Session { var $username; //Username given on sign-up var $userid; //Random value generated on current login var $userlevel; //The level to which the user pertains var $time; //Time user was last active (page loaded) var $logged_in; //True if user is logged in, false otherwise var $userinfo = array(); //The array holding all user info var $url; //The page url current being viewed var $referrer; //Last recorded site page viewed /** * Note: referrer should really only be considered the actual * page referrer in process.php, any other time it may be * inaccurate. */ /* Class constructor */ function Session(){ $this->time = time(); $this->startSession(); } /** * startSession - Performs all the actions necessary to * initialize this session object. Tries to determine if the * the user has logged in already, and sets the variables * accordingly. Also takes advantage of this page load to * update the active visitors tables. */ function startSession(){ global $database; //The database connection session_start(); //Tell PHP to start the session /* Determine if user is logged in */ $this->logged_in = $this->checkLogin(); /** * Set guest value to users not logged in, and update * active guests table accordingly. */ if(!$this->logged_in){ $this->username = $_SESSION['username'] = GUEST_NAME; $this->userlevel = GUEST_LEVEL; $database->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time); } /* Update users last active timestamp */ else{ $database->addActiveUser($this->username, $this->time); } /* Remove inactive visitors from database */ $database->removeInactiveUsers(); $database->removeInactiveGuests(); /* Set referrer page */ if(isset($_SESSION['url'])){ $this->referrer = $_SESSION['url']; }else{ $this->referrer = "/"; } /* Set current url */ $this->url = $_SESSION['url'] = $_SERVER['PHP_SELF']; } /** * checkLogin - Checks if the user has already previously * logged in, and a session with the user has already been * established. Also checks to see if user has been remembered. * If so, the database is queried to make sure of the user's * authenticity. Returns true if the user has logged in. */ function checkLogin(){ global $database; //The database connection /* Check if user has been remembered */ if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookid'])){ $this->username = $_SESSION['username'] = $_COOKIE['cookname']; $this->userid = $_SESSION['userid'] = $_COOKIE['cookid']; } /* Username and userid have been set and not guest */ if(isset($_SESSION['username']) && isset($_SESSION['userid']) && $_SESSION['username'] != GUEST_NAME){ /* Confirm that username and userid are valid */ if($database->confirmUserID($_SESSION['username'], $_SESSION['userid']) != 0){ //Variables are incorrect, user not logged in unset($_SESSION['username']); unset($_SESSION['userid']); return false; } /* User is logged in, set class variables */ $this->userinfo = $database->getUserInfo($_SESSION['username']); $this->username = $this->userinfo['username']; $this->userid = $this->userinfo['userid']; $this->userlevel = $this->userinfo['userlevel']; return true; } /* User not logged in */ else{ return false; } } /** * login - The user has submitted his username and password * through the login form, this function checks the authenticity * of that information in the database and creates the session. * Effectively logging in the user if all goes well. */ function login($subuser, $subpass, $subremember){ global $database, $form; //The database and form object /* Username error checking */ $field = "user"; //Use field name for username if(!$subuser || strlen($subuser = trim($subuser)) == 0){ $form->setError($field, "* Username not entered"); } else{ /* Check if username is not alphanumeric */ if(!preg_match("^([0-9a-z])*$^i", $subuser)){ $form->setError($field, "* Username not alphanumeric"); } } /* Password error checking */ $field = "pass"; //Use field name for password if(!$subpass){ $form->setError($field, "* Password not entered"); } /* Return if form errors exist */ if($form->num_errors > 0){ return false; } /* Checks that username is in database and password is correct */ $subuser = stripslashes($subuser); $result = $database->confirmUserPass($subuser, md5($subpass)); /* Check error codes */ if($result == 1){ $field = "user"; $form->setError($field, "* Username not found"); } else if($result == 2){ $field = "pass"; $form->setError($field, "* Invalid password"); } /* Return if form errors exist */ if($form->num_errors > 0){ return false; } /* Username and password correct, register session variables */ $this->userinfo = $database->getUserInfo($subuser); $this->username = $_SESSION['username'] = $this->userinfo['username']; $this->userid = $_SESSION['userid'] = $this->generateRandID(); $this->userlevel = $this->userinfo['userlevel']; /* Insert userid into database and update active users table */ $database->updateUserField($this->username, "userid", $this->userid); $database->addActiveUser($this->username, $this->time); $database->removeActiveGuest($_SERVER['REMOTE_ADDR']); /** * This is the cool part: the user has requested that we remember that * he's logged in, so we set two cookies. One to hold his username, * and one to hold his random value userid. It expires by the time * specified in constants.php. Now, next time he comes to our site, we will * log him in automatically, but only if he didn't log out before he left. */ if($subremember){ setcookie("cookname", $this->username, time()+COOKIE_EXPIRE, COOKIE_PATH); setcookie("cookid", $this->userid, time()+COOKIE_EXPIRE, COOKIE_PATH); } /* Login completed successfully */ return true; } /** * logout - Gets called when the user wants to be logged out of the * website. It deletes any cookies that were stored on the users * computer as a result of him wanting to be remembered, and also * unsets session variables and demotes his user level to guest. */ function logout(){ global $database; //The database connection /** * Delete cookies - the time must be in the past, * so just negate what you added when creating the * cookie. */ if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookid'])){ setcookie("cookname", "", time()-COOKIE_EXPIRE, COOKIE_PATH); setcookie("cookid", "", time()-COOKIE_EXPIRE, COOKIE_PATH); } /* Unset PHP session variables */ unset($_SESSION['username']); unset($_SESSION['userid']); /* Reflect fact that user has logged out */ $this->logged_in = false; /** * Remove from active users table and add to * active guests tables. */ $database->removeActiveUser($this->username); $database->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time); /* Set user level to guest */ $this->username = GUEST_NAME; $this->userlevel = GUEST_LEVEL; } /** * register - Gets called when the user has just submitted the * registration form. Determines if there were any errors with * the entry fields, if so, it records the errors and returns * 1. If no errors were found, it registers the new user and * returns 0. Returns 2 if registration failed. */ function register($subuser, $subpass, $subemail){ global $database, $form, $mailer; //The database, form and mailer object /* Username error checking */ $field = "user"; //Use field name for username if(!$subuser || strlen($subuser = trim($subuser)) == 0){ $form->setError($field, "* Username not entered"); } else{ /* Spruce up username, check length */ $subuser = stripslashes($subuser); if(strlen($subuser) < 5){ $form->setError($field, "* Username below 5 characters"); } else if(strlen($subuser) > 30){ $form->setError($field, "* Username above 30 characters"); } /* Check if username is not alphanumeric */ else if(!preg_match("^([0-9a-z])+$^", $subuser)){ $form->setError($field, "* Username not alphanumeric"); } /* Check if username is reserved */ else if(strcasecmp($subuser, GUEST_NAME) == 0){ $form->setError($field, "* Username reserved word"); } /* Check if username is already in use */ else if($database->usernameTaken($subuser)){ $form->setError($field, "* Username already in use"); } /* Check if username is banned */ else if($database->usernameBanned($subuser)){ $form->setError($field, "* Username banned"); } } /* Password error checking */ $field = "pass"; //Use field name for password if(!$subpass){ $form->setError($field, "* Password not entered"); } else{ /* Spruce up password and check length*/ $subpass = stripslashes($subpass); if(strlen($subpass) < 4){ $form->setError($field, "* Password too short"); } /* Check if password is not alphanumeric */ else if(!preg_match("^([0-9a-z])+$^", ($subpass = trim($subpass)))){ $form->setError($field, "* Password not alphanumeric"); } /** * Note: I trimmed the password only after I checked the length * because if you fill the password field up with spaces * it looks like a lot more characters than 4, so it looks * kind of stupid to report "password too short". */ } /* Email error checking */ $field = "email"; //Use field name for email if(!$subemail || strlen($subemail = trim($subemail)) == 0){ $form->setError($field, "* Email not entered"); } else{ /* Check if valid email address */ $regex = "^[_+a-z0-9-]+(\\.[_+a-z0-9-]+)*" ."@[a-z0-9-]+(\\.[a-z0-9-]{1,})*" ."\\.([a-z]{2,}){1}$^"; if(!preg_match($regex,$subemail)){ $form->setError($field, "* Email invalid"); } $subemail = stripslashes($subemail); } /* Errors exist, have user correct them */ if($form->num_errors > 0){ return 1; //Errors with form } /* No errors, add the new account to the */ else{ if($database->addNewUser($subuser, md5($subpass), $subemail)){ if(EMAIL_WELCOME){ $mailer->sendWelcome($subuser,$subemail,$subpass); } return 0; //New user added succesfully }else{ return 2; //Registration attempt failed } } } /** * editAccount - Attempts to edit the user's account information * including the password, which it first makes sure is correct * if entered, if so and the new password is in the right * format, the change is made. All other fields are changed * automatically. */ function editAccount($subcurpass, $subnewpass, $subemail){ global $database, $form; //The database and form object /* New password entered */ if($subnewpass){ /* Current Password error checking */ $field = "curpass"; //Use field name for current password if(!$subcurpass){ $form->setError($field, "* Current Password not entered"); } else{ /* Check if password too short or is not alphanumeric */ $subcurpass = stripslashes($subcurpass); if(strlen($subcurpass) < 4 || !preg_match("^([0-9a-z])+$^", ($subcurpass = trim($subcurpass)))){ $form->setError($field, "* Current Password incorrect"); } /* Password entered is incorrect */ if($database->confirmUserPass($this->username,md5($subcurpass)) != 0){ $form->setError($field, "* Current Password incorrect"); } } /* New Password error checking */ $field = "newpass"; //Use field name for new password /* Spruce up password and check length*/ $subpass = stripslashes($subnewpass); if(strlen($subnewpass) < 4){ $form->setError($field, "* New Password too short"); } /* Check if password is not alphanumeric */ else if(!preg_match("^([0-9a-z])+$^", ($subnewpass = trim($subnewpass)))){ $form->setError($field, "* New Password not alphanumeric"); } } /* Change password attempted */ else if($subcurpass){ /* New Password error reporting */ $field = "newpass"; //Use field name for new password $form->setError($field, "* New Password not entered"); } /* Email error checking */ $field = "email"; //Use field name for email if($subemail && strlen($subemail = trim($subemail)) > 0){ /* Check if valid email address */ $regex = "^[_+a-z0-9-]+(\\.[_+a-z0-9-]+)*" ."@[a-z0-9-]+(\\.[a-z0-9-]{1,})*" ."\\.([a-z]{2,}){1}$^"; if(!preg_match($regex,$subemail)){ $form->setError($field, "* Email invalid"); } $subemail = stripslashes($subemail); } /* Errors exist, have user correct them */ if($form->num_errors > 0){ return false; //Errors with form } /* Update password since there were no errors */ if($subcurpass && $subnewpass){ $database->updateUserField($this->username,"password",md5($subnewpass)); } /* Change Email */ if($subemail){ $database->updateUserField($this->username,"email",$subemail); } /* Success! */ return true; } /** * isAdmin - Returns true if currently logged in user is * an administrator, false otherwise. */ function isAdmin(){ return ($this->userlevel == ADMIN_LEVEL || $this->username == ADMIN_NAME); } /** * generateRandID - Generates a string made up of randomized * letters (lower and upper case) and digits and returns * the md5 hash of it to be used as a userid. */ function generateRandID(){ return md5($this->generateRandStr(16)); } /** * generateRandStr - Generates a string made up of randomized * letters (lower and upper case) and digits, the length * is a specified parameter. */ function generateRandStr($length){ $randstr = ""; for($i=0; $i<$length; $i++){ $randnum = mt_rand(0,61); if($randnum < 10){ $randstr .= chr($randnum+48); }else if($randnum < 36){ $randstr .= chr($randnum+55); }else{ $randstr .= chr($randnum+61); } } return $randstr; } }; //************************************** // Page load dropdown results // //************************************** function getTierOne() { $result = mysql_query("SELECT * FROM catagories ORDER BY name ASC") or die(mysql_error()); while($tier = mysql_fetch_array( $result )) { echo '<option value="'.$tier['id'].'">'.$tier['name'].'</option>'; } } //************************************** // First selection results // //************************************** if($_GET['func'] == "drop_1" && isset($_GET['func'])) { drop_1($_GET['drop_var']); } function drop_1($drop_var) { $result = mysql_query("SELECT * FROM courses WHERE pid='$drop_var'") or die(mysql_error()); echo '<select name="tier_two" id="tier_two"> <option value=" " disabled="disabled" selected="selected">Choose one</option>'; while($drop_2 = mysql_fetch_array( $result )) { echo '<option value="'.$drop_2['id'].'">'.$drop_2['name'].'</option>'; } echo '</select> '; echo '<input type="submit" name="submit" value="Submit" />'; } /** * Initialize session object - This must be initialized before * the form object because the form uses session variables, * which cannot be accessed unless the session has started. */ $session = new Session; /* Initialize form object */ $form = new Form; ?> Hi, I was just wondering about the necessity of using cookies and session_start() to preserve state and provide personalization. Why can't it be done this way: The user logs in, the script adds the IP address of the client, together with his account info (say user id), and browser name, to a MySQL table, and configures the table (by setting a MySQL event) to delete that row after, say, 30 days (if not the user logs out in between, in which case the row is explicitly deleted). Now each time a page request comes from that client through that browser(as verified by grabbing the IP address and browser info), a check in the session table is done to see whether that IP address is in that table. If yes, it means that a user is logged in, and after grabbing the user id (necessary, because many users can log in from the same IP, whether from one or more than one browser), an accordingly personalized page is sent to the client. If no, then it sends just a normal page. Is it feasible or possible? This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=351208.0 this problem really drives me crazy..hope that anyone could help. I left my page only with <?php session_start(); ?> with no script at all..and i still got error Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at E:\Program Files\XAMPP 1.5.4\xampp\htdocs\folder\page1.php:1) in E:\Program Files\XAMPP 1.5.4\xampp\htdocs\folder\page1.php on line 2 No white space at all. I tried to upload this file into the server (not local) and no error appeared. but when i run it in my local server, error appeared. I restart my xampp so many times but still didn't fix this. what's the problem then? thanks in advance I am getting the following error mesages when I view the index page at http://www.voltageking.com/exams/. I have no idea why this would be ocurring. I did not write the PHP code. The code was written by an ex-employee who is no longer able to be contacted. I thought perhaps these errors are ocurring because I reinstalled the files overwriting the older files and it perhaps changed the permissions, but I went to the directory and changed the directory and file permissions to all and it still gave me the identical error messages. Below in RED is the text which apears when you view http://www.voltageking.com/exams/ . Warning: session_start() [function.session-start]: open(/var/chroot/home/content/v/o/l/voltageking/tmp/sess_b8c8479843aced59a006557ec7b499ff, O_RDWR) failed: No such file or directory (2) in /home/content/v/o/l/voltageking/html/exams/index.php on line 2 Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home/content/v/o/l/voltageking/html/exams/index.php:2) in /home/content/v/o/l/voltageking/html/exams/index.php on line 2 Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/content/v/o/l/voltageking/html/exams/index.php:2) in /home/content/v/o/l/voltageking/html/exams/index.php on line 2 It is refering to line 2 of the index.php file which I have pasted below in BLUE: <?php session_start(); $_SESSION['logged']="none"; ?> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Power Learning Systems Online Practice Tests</title> <link rel="stylesheet" type="text/css" media="screen" href="css/Test-CSS.css" /> <style type="text/css" title="currentStyle" media="screen"> @import "css/Test-CSS.css"; #wrapper { position: absolute; bottom: 50%; right: 50%; height: 600px; width: 745px; } #container { position: relative; left: 50%; top: 50%; } #loginArea{ position:absolute; width:749px; height:570px; z-index:1; background-image: url(images/login-bgs.jpg); background-repeat: no-repeat; overflow: visible; } #PLSlogo { position:absolute; width:282px; height:117px; z-index:2; left: 208px; top: 97px; } #login { position:absolute; width:294px; height:32px; z-index:2; left: 269px; top: 399px; text-align: center; } #password { position:absolute; width:100px; height:25px; z-index:2; left: 163px; top: 403px; text-align: right; font-family: Verdana, Geneva, sans-serif; font-size: 14px; font-weight: normal; color: #024572; } .pass { margin-top: 0px; margin-bottom: 0px; font-family: Verdana, Geneva, sans-serif; font-size: 13px; color: #000; text-align: left; text-indent: 0px; border-top-width: 1px; border-right-width: 2px; border-bottom-width: 2px; border-left-width: 1px; border-top-style: solid; border-right-style: solid; border-bottom-style: solid; border-left-style: solid; border-top-color: #003466; border-right-color: #003466; border-bottom-color: #003466; border-left-color: #003466; width: 202px; } #intro { position:absolute; width:511px; height:36px; z-index:2; left: 122px; top: 251px; font-family: Verdana, Geneva, sans-serif; font-size: 20px; color: #064473; font-weight: bold; text-align: center; } #moreinfo { position:absolute; width:500px; height:18px; z-index:2; left: 128px; top: 282px; font-family: Verdana, Geneva, sans-serif; font-size: 12px; color: #064473; text-align: center; } #message1 { position:relative; width:540px; height:28px; z-index:2; left: 104px; top: 360px; font-family: Verdana, Geneva, sans-serif; font-weight: normal; color: #F00; text-align: center; } #apDiv1 { position:relative; width:200px; height:20px; z-index:3; left: 510px; top: 508px; font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666; text-align: right; } #apDiv1 a{ font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666; text-decoration: none; } #apDiv1 a:hover{ font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #000000; text-decoration: none; } #apDiv2 { position:relative; z-index:1; left: 54px; top: 420px; text-align: center; height: 32px; width: 644px; } </style> <body bgcolor="#EAEDF4"> <span> <div id="wrapper"> <div id="container"> <div id="loginArea"> <div id="message1"><?php echo $_SESSION['message1']; ?></div> <div id="apDiv1">Powered by <a href="http://www.VoltageKing.com" target="_blank">VoltageKing.com</a></div> <div id="PLSlogo"><a href="http://www.4ezhelp.com/" target="_blank"><img src="http://www.4ezpass.com/images/PLS_main_logo.jpg" border="0"/></a></div> <div id="intro">Online Examination Preparation Interface</div> <div id="moreinfo">For more information about Power Learning Systems Online Tests <a href="http://www.voltageking.com/pages.php?CDpath=0&pID=54">click here</a></div> <div id="password">Password:</div> <div id="login"> <form id="form1" name="form1" method="post" action="login.php"> <input type="hidden" value="http://www.4ezpass.com" name="sender"> <input name="pass" type="password" class="pass" maxlength="20" /> <input name="login" type="submit" value="login" /> </form> </div> <div id="apDiv2"><img src="http://www.4ezpass.com/images/PPP.jpg" border="0"/></div> </div> </div> </div> </span> <?php $_SESSION['message1']=" "; $_SESSION['message2']=" "; ?> <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> try { var pageTracker = _gat._getTracker("UA-15438543-9"); pageTracker._trackPageview(); } catch(err) {}</script> </body> </html> Any help would be greatly appreacated! Steve :-) I have an include file that is included in every page of my website. I'm using sessions and trying to streamline code. The very first line of any page is my include file, and the very first thing in that file is: Code: [Select] <?php session_start(); ?> The page doesn't register that a session was started. Do I have to have session_start() on every single page? Or is there a way to have it in my include file so it is automatically on every page for me? Thank you! Hi Everyone I am having a few issues with my website. I have developed in on my xampp local host and it works ok but when I upload the files and try to renew a membership using stripe I get the following messages. Warning: session_start(): Cannot start session when headers already sent in /customers/a/d/f/mywebsite.co.uk/httpd.www/mywebsite/inc/settings.php on line 2 Warning: Cannot modify header information - headers already sent by (output started at /customers/a/d/f/mywebsite.co.uk/httpd.www/mywebsite/procedures/payments/charge.php:1) in /customers/a/d/f/mywebsite.co.uk/httpd.www/mywebsite/procedures/payments/charge.php on line 141 I have some includes that appear on every page. This is the bootstrap.php file. This file holds the settings.php which connects to my database and other function files. In this settings page I call the session_start() php function and then connect to my database. I call the bootstrap.php file on every page to there for call the session_start() on every page. I am using sessions alot so is this the right thing to do? I have attached the renew_membership payment page which holds the form. The user fills out the payment page and the form data gets sent to a script called charge.php which uses the stripe objects to make the payment. I then want to do a redirect to the paymentSuccess.php page to output to the user that the payment was made successfully. This is where the issues arrise. I have split the charge file into 3 screen shots so it is more readable. Hope someone can help me. Thanks a lot David
Edited April 26 by Irish_Dave in this page http://maximaart.com/newscp/ i have this problem Code: [Select] Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/maximasy/public_html/newscp/index.php:1) in /home/maximasy/public_html/newscp/index.php on line 2 my source code is <?php session_start(); include_once("config.php"); include_once("functions.php"); $errorMessage = ''; if (isset($_POST['txtUserId']) && isset($_POST['txtPassword'])) { if ($_POST['txtUserId'] === "$user" && $_POST['txtPassword'] === "$pass") { // the user id and password match, $_SESSION['basic_is_logged_in'] = true; require("main.php"); exit;?> I am having trouble resolving an error. Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/s519970/public_html/header.php:27) in /home/s519970/public_html/admin/login.php on line 2 What I can gather is I can't use "header (Location: 'admin.php')" after i've used session_start(). I have tried to replace the header (Location: 'admin.php') with this: echo "<script>document.location.href='admin.php'</script>"; echo "<script>'Content-type: application/octet-stream'</script>"; I've been trying to read up on solutions but haven't been able to get it sorted. If anyone can offer some advice that would be greatly appreciated as im new to php. Code: [Select] <?php session_start(); if(isset($_SESSION['user'])) echo "<script>document.location.href='admin.php'</script>"; echo "<script>'Content-type: application/octet-stream'</script>"; ?> <div id="loginform"> <form action="dologin.php" method="post"> <table> <tr> <td><span>Username:</span></td> <td><input type="text" name="username" /></td> </tr> <tr> <td><span>Password:</span></td> <td><input type="password" name="password" /></td> </tr> <tr> <td colspan="2" align="right"><input type="submit" name="login" value="Login" /></td> </tr> </table> </form> </div> I have tried using require_once('yourpage.php'); before my <head></head> tags in the header document where I've specified the html information but this doesn't seem to work. I've been advised to use ob_start("ob_gzhandler"); but I am not sure how to implement this. Any advice is greatly appreciated! I am trying to create an index page which contains registration and login field the problem that i get is on successful login a warning is displayed session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\xampp\htdocs\Eventz.com\index.php:116) in C:\xampp\htdocs\Eventz.com\index.php on line 235 This is the login part of my index.php this tag is inside an html table below the login form I also have a registration form and its php code above the login form Code: [Select] <?php if (isset($_REQUEST['pass'])) { $id=$_POST['id']; $pass=$_POST['pass']; $conn =mysql_connect("localhost","root",""); if (!$conn) { die('Could not connect: ' . mysql_error()); } /* checking connection....success! */ $e=mysql_select_db('test', $conn); if(!$e) { die(''.mysql_error()); } else { echo 'database selected successfully'; } if (isset($_REQUEST['id']) || (isset($_REQUEST['pass']))) { if($_REQUEST['id'] == "" || $_REQUEST['pass']=="") { echo "login fields cannot be empty"; } else { $sql=mysql_query("Select email,password from login where email='$id' AND password='$pass'"); $count=mysql_num_rows($sql); if($count==1) /* $count checks if username and password are in same row */ { session_start(); $_SESSION['id']=$id; echo "</br>Login Successful</br>"; } else { echo "</br>invalid</br>"; echo "please try to login again</br>"; } } } } ?> Any help or suggestion would be appreciated |