Reputation: 194
I've created a login which sets a session variable to the users id which I get from my database. After the user clicks login after entering their details I redirect them to the home page which uses the session variable to get the users id for display purposes. The problem I am having is with the session variable. This is what my code looks like (simplified):
$_SESSION['user_id'] = $User_id;
header('Location: http://localhost/Projects/Login/home.php');
exit();
This is the snippet of code which sets my session variable, I have tested an it works. The next snippet of code is the function which is called from the home page (home.php). It is used to check if the user is logged in or not
function logged_in(){
return isset($_SESSION['user_id']);
}
I then use this if statement to perform different displays based on whether the user is logged in or not, again it has been simplified.
if( logged_in() === true ){
$session_user_id = $_SESSION['user'];
print "logged in";
}
else{
print "not logged in";
}
The problem seems to be with the if statement as it unsets the session variable to an empty array. If I print out the session variable I get Array(). I have started a session on each of the pages.
Upvotes: 1
Views: 716
Reputation: 1213
There seem to be two issues here.
First is the array keys; you're using user
in one case and user_id
in the other.
The second is speculative; you said it results in an empty array (I assume you have var_dump($_SESSION)
or similar to confirm this?). If so it suggests you haven't started the session. You need to call session_start();
to get access to the session data.
Each time your script runs it needs to get access to the sessions stored on the server, this is why you run session_start()
. The long version is that it obtains a lock on the local file which stores the session data (leading to whats known as session locking). As a result you may (for longer running scripts and/or performance) wish to call session_write_close()
when you're finished with the $_SESSION
superglobal.
Upvotes: 2