0
votes

I am a complete noob at php sessions. I've gotten them working before, but never on a live server, just on my local testing environment.

My problem is that the $_SESSION variable is always an empty array (not undefined).

This is for a login form that is making an AJAX call to a php file.

Here is the AJAX call:

$.ajax({
        url: 'xhr/login.php',
        data: $(this).serialize(),
        type: 'post',
        dataType: 'json',
        success: function(result){
            if (result.success){
                console.log(result);
            };
        },
        error: function(e){console.log("Could not retrieve login information")}
    });

Here are the relevant parts of the login script:

# Start the user session
if(!isset($_SESSION)) {
    session_start();
    session_regenerate_id();
};

# Set our session values
                WHILE($session_row = mysql_fetch_assoc($session_result)){
                    $_SESSION['id'] = $session_row['id'];
                    $_SESSION['last_login'] = $session_row['last_login'];
                    $_SESSION['username'] = $session_row['username'];
                    $_SESSION['signup_date'] = $session_row['signup_date']; 
                };

I have the returning Json returning the session variable as:

echo json_encode(array("success"=>"user logged in", "session"=>$_SESSION));

but when I log the result.session variable to the console, it simply returns an empty array.

1
Why is while capitalized? Where are you making this database query? - Charles Sprayberry
where is $session_result being generated? If no errors are being generated, it may be that "$session_row = mysql_fetch_assoc($session_result)" never returns true, so the loop is ignored. Also, as Charles asked, it should be "while", not WHILE. - Ben D

1 Answers

1
votes

My problem is that the $_SESSION variable is always an empty array (not undefined).

That's totally normal for every session that has been successfully started.

session_regenerate_id();

ouch. ouch. ouch. Why do you regenerate the id out of the blue on every request?

Remove that line. It might also cause your problem.