Search code examples
phpajaxsession-variables

PHP Session variable not persisting across pages


I'm working on a web app. After a user logs in, a $_SESSION variable named user should be stored. However, when I try to access it later I am unable to.

Both login.php and settings.php are accessed via AJAX and displayed in a modal window.

login.php:

<?PHP
require("require/connect.php"); 
$errors = array();
$passed=FALSE;
if(isset($_POST['username']) && isset($_POST['password'])){
     /* Check db, no output */
     if($record->password != $password){ ?>
          /* Output login fail message */
     <?PHP }else if(intval($record->confirmed)!=1){ ?>
          /* Output email not cofirmed message */
     <?PHP }else{ ?>
         $user = clone $record;
         unset($user->password);
         session_start();
         $_SESSION['user']=$user;
         print_r($_SESSION);
         /*output success message*/
     <?PHP }; 
}else{ /*output login form*/ } ?>
     

prints out:

settings.php

<?PHP
require("require/connect.php");
require("require/userdata.php");
/*other stuff*//

require/userdata.php

<?PHP session_start();
print_r($_SESSION);

prints out:

Array ( )

Solution

  • In login.php I had to move session_start() above require("require/connect.php");. Even the directly next line didn't work.

    Not sure why this changed anything, since connect.php is only too lines and no output.

    connect.php

    <?PHP 
    mysql_connect(/**/)or die("Couldn't connect to MySQL database");    
    mysql_select_db(/**/) or die("Couldn't select MySQL database in connect.php");
    ?>