Sometimes Session variables stop working - php

I've had this twice now. Out of the blue, my log-in system stops working, and by debugging I find out the $_SESSION variable does not survive the log-in process. Then, without an obvious cause, it resumes working. Here's the flow:
User logs in at index.html, form submits to login.php;
login.php does basic sanity, isset and empty checks, then checks the credentials with the database. If the email address and password are correct (i.e., exist in the database) put them in the $_SESSION variable and redirect user to home.php.
home.php retrieves the $_SESSION variables. Here it fails.
The second time (a few minutes ago) I read more about it and found a forum thread I hadn't read the previous time it happened (I stopped reading about it when session variables worked again) which said you need to have <?php instead of <? before session_start();. I tried it, not expecting it to work, but when I logged in, directly after changing that (and that was the only thing I changed AFAIK) it worked. Cause found? Let's check after changing <?php back to <?. It still works. What can be the cause of this and how can I prevent it (or, if it can't be prevented, detect what's going on)?
Edit:
Something interesting: I've got a small utility function to check if the user is logged in:
function assertUserLogin() {
try {
$user = new User($_SESSION['email'], $_SESSION['pwd']);
} catch(Exception $ex){
writeToLog("Exception: " . $ex->getMessage());
header("Location: http://www.korilu.nl/maurits/anw?requested:" . $_SERVER["REQUEST_URI"]);
}
writeToLog($user->email . " logged in\n");
return $user;
}
So I can just do this:
<?
session_start();
$user = assertUserLogin();
?>
On every page the user needs to be logged in. The interesting thing here is, that if it fails (as described above), it calls my function writeToLog() (log() is already taken by the PHP standard library):
function writeToLog($string) {
$log = fopen("log.txt", "w");
fwrite($log, $string);
fclose($log);
}
which is pretty simple. But the log remains empty. (I am sure the function writeToLog() gets called, because I get redirected to http://www.korilu.nl/maurits/anw?requested:/maurits/anw/home.php. The assertUserLogin() function is the only place that does that.)

Try session_write_close(); at all places where the script ends like exit; die(); and page end.

I found out it is a browser-specific issue. It was caused by Google Chrome, I think, because it vanishes as soon as I use mobile Safari or Mozilla Firefox to test the Sessions. Although in the advanced settings I could see the PHPSESSID cookie, it didn't pickup the session.
Important edit
I was wrong. Mozilla started to drop the session too. After I deleted the session (session_destroy()) it worked again though. So my guess is that after the session expires on the server, the browser still has the PHPSESSID cookie. If it sends that to the server, the server can't find the session and just puts an empty array in $_SESSION, leaving me clueless. I hope this helps somebody having the same problem.

Related

is there a delay in setting session variables? failing on first attempt only

I have a page, login.php, that processes a username and password and if successful it sets session variables and then redirects the user to home.php. The relevant part of login.php is here:
if ($pwdHash == $storedpass) {
$success = true;
$sessionStatus = session_status();
if ($sessionStatus !== PHP_SESSION_ACTIVE) {
session_start();
}
$_SESSION['user_id'] = $user;
$_SESSION['logged_in'] = true;
session_write_close();
header('Location: http://www.examplesite.com/home.php');
header("HTTP/1.1 303 See Other");
die("redirecting");
}
Then home.php tries to collect the session variable
$sessionStatus = session_status();
if ($sessionStatus !== PHP_SESSION_ACTIVE) {
session_start();
}
$loggedIn = $_SESSION['logged_in'];
The problem is that on the first login attempt, $_SESSION['logged_in'] is undefined and generates an error, even though login.php was successful.
Notice: Undefined index: logged_in
A var_dump of $_SESSION returns an empty array, but sessionStatus reports that the session was already started, it did not have to execute session_start.
This forces the user to log in a second time, then everything is fine. So is the redirect just happening too fast for the session variable to get set? Should I put a delay in the redirect? (and how would I do that?) Or is this something else that I'm doing wrong?
EDIT: I've checked with my host based on an answer to a similar question and confirmed that a session would never be served by more than one server and there is no need to enable sticky sessions or anything like that. I've also updated the code above based an answer offered below and some other research but the error persists.
The session is probably automatically saved when the script ends. You redirect before the script ends.
How long your script takes to really end depends very much on what other code needs to wind down. It is better to explicitly save the session.
How to do this depends on what kind of sessions you use. One type can be closed like this:
http://php.net/manual/en/function.session-write-close.php
If that's the one you're using do this:
if ($pwdHash == $storedpass) {
$success = true;
$_SESSION['user_id'] = $user;
$_SESSION['logged_in'] = true;
session_write_close();
header('Location: http://www.examplesite.com/home.php');
header("HTTP/1.1 303 See Other");
die("redirecting");
}
And the session should be available to the next page when you redirect.
If your sessions work differently, you have to adapt the code, of course. The point I'm trying to make is: Never put a delay in your code. It's unreliable, and pointless. Simply save the session before you redirect.
I have experienced the same issue while writing the session content to the database.
To make it work I have added the sleep() function before setting the session variable, just like below.
sleep(2);
$_SESSION['GUID'] = uniqid(time().rand());
It resolves the issue for me.
We have observed this issue when the page hits are frequent but if one or two users are accessing the page it works as expected.
I have encountered this same issue with a login page but none of the suggestions work for me. The only thing I've found that does work is redirecting the page to itself after 1 second and then checking the session variables to see if the login was successful...
startSession(); // assigns all the login session variables, etc.
header('Refresh: 1; URL=/[THIS_PAGE].php'); // [THIS_PAGE] = the current login page
However, this is a very inelegant solution and I don't like using it. But it "works".
This problem persists. In my case, the user login goes without a problem to the protected homepage, but clicking on a menu link causes the user to be dumped back to the login page to login again. A check on certain Session values (required for both pages) shows these are not set on going to the specific menu link (while other menu links cause no problem). The code requiring a session value is the same in all cases. Not all users experience the problem. Seems that those with less robust connections to the internet always experience this problem. Others, never.

Session variables not being created if the user doesn't log out before logging back in

When the user logs in, multiple session variable are created and work perfectly.
When they sign out and log in again it works.
However, when someone quits out of their browser without signing out, the next time they log in no session variables are created.
To sign out, one goes to my logout.php file. The code in my logout.php file is:
<?php
session_start();
session_destroy();
echo '<meta http-equiv="refresh" content=".000001;url=index.php">';
?>
I've tried pasting the code at the start of my index.php (where the login form is) but it doesn't work unless you go to the logout.php file.
Why is this and how do i fix it?
There are some possible situations:
First and main reason:
If you have already started session_start(), server may be dump error, while you trying to create new, if your errors are off, you can't see them.
Second: You do check before session destroy.
You are destroying the session before you are making sure that no session variables remain.
I would delete all of the session variables first before you destroy it, to be safe, because sometimes some get left behind. You can do this like so
if (isset($_SESSION['/*whatever session variables you are using*/'])) {
$_SESSION = array();
session_destroy();
}
Also if you are using any cookies for any reason (though this may not be the case), you need to make sure those are also deleted. something like this:
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(),'',time() - 3600);
}

Using session variable to use info on different pages

i'm having a bit of a problem. I'm trying to set up a simple webpage with only three .php pages. I want a session variable $_SESSION['userID'] to be set when a user is logged in and I want the index page to show extra info if someone is logged in.
On index.php I want to show some info, if a user is logged in I want to show some extra info.
login.php - simple log in form.
login_exe.php - takes care of database connection and verification.
So this was my idea:
On index.php, check if session is started, if not: start.
<?php
if (!isset($_SESSION)) {
session_start();
echo "session started";
}
later on, check if $_SESSION['userID'] contains a value, if so: print a string
if($_SESSION['userID'] != null){
echo "User logged in";
}
On login_exe.php i've almost the same code:
<?php
if (!isset($_SESSION)) {
session_start();
echo "session started";
}
in verification function:
$_SESSION['userID'] = $data['userID'];
header("Location: index.php");
The problem is that a new session is started on every page. How can I fix this and only start the session once? Thanks in advance
You should just put session_start() on top of documents that using sessions. Say, if you have 5 .php files that using sessions, then put 5 times the session_start() on top of them.
This is because session_start() sends headers and headers must be sent before any output (for example, any echo or whitespace).
Then, you should use something like isset($_SESSION["foo"]) and not just the entire $_SESSION array, where foo is something you set previously.
If you dont want sessions at all or need to reset the entire array, just call session_destroy() which effectively destroy the current session. Use unset($_SESSION["foo"]) when you want to get rid of a key.
Finally, you might get weird cases where you cannot read session key you write at. In these cases check what is the path of sessions and if they're writeable, or change their path:
$path = session_save_path(); // what is the path
is_writable($path); // can i write to it?
session_save_path("my/new/path"); // change the darn path;
// put -even- before session_start()!
:)
glad i help
I think the PHP manuals are really good compared to ...ahm, so just read about session_start(). It says:
session_start() creates a session or resumes the current one (...)
so all you need is session_start() very early in your code. This must be executed on every request (maybe as include).
Your code checking the userId looks fine, one important hint here: you should know exactly what isset(), empty() and the like mean in PHP, so always have the comparision of comparison at hand.
You should not ask new answers (edit: questions) in comments. Be as systematic here as you are in coding.
How to end a session:
This gives room for discussion, because there is the session cookie, which is client side, and the session data, which is server side.
I recommend:
$_SESSION = null;
Reason: this will clear all login and other associated data immediately. It leaves the cookie intact, which is normally of no concern, since all associated data is gone.

PHP Session Variables not saving after redirect?

I seem to be having a strange problem all the sudden and I was hoping someone may have a suggestion...
I have a login script that is supposed to register a session variable containing an error message if the login fails and then redirect the user to the page they came from. For example the user may have used the forum on index.php and the login fails and they are returned to index.php where a script displays the error message contained in the session variable.
However, the session variables do not appear to be saving. For the record, I am using session_start() in the login script as well as any page that has a login form that should display the error message if the user is returned to that page because the login failed.
My script is as follows:
if (isset($_POST['prev'])) {
$prev = $_POST['prev'];
}
else {
$prev = "login.php";
}
$_SESSION['Login_Error'] = $error;
header("Location: $prev");
Then the script on the form pages is:
if (isset($_SESSION['Login_Error'])) {
echo $_SESSION['Login_Error'];
}
And the error I am getting is:
Notice: Undefined index: Login_Error in F:\EasyPHP-12.0\www\index.php on line 3
Any ideas as to why it isn't saving? If the login is successful the script sets a user id session variable which is working fine. Thanks for any suggestions.
I have had this problem before. If the session variable is set while the user is on
www.domain.com/login.php
and the user is redirected to
domain.com/index.php (without the www. at the beginning)
The session variable will not be accessible. Make sure that the www. is either always there, never there, or that your script uses it or not depending on the circumstance.
At some point further down the line, if you have: unset($_SESSION['Login_Error']) or similar.. . like $_SESSION['Login_Error'] = null for example.. this can cause an issue.
The reason this is - is that after the header to redirect is sent - the rest of the php script continues to execute.
If you place a die() or exit() after the header.. this should then stop the rest of the script executing and thus, make sure the var isn't unset at any point further down the script.
Hope this helps.
You require to start session before you declare session variables:
http://php.net/manual/es/function.session-start.php
also there is a bug on slowly machines where can't save session variables just at the moment.
try using a timeout header:
header("refresh:3;url=".$prev);
See more about refresh header at http://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Refresh

PHP: session isn't saving before header redirect

I have read through the php manual for this problem and it seems quite a common issue but i have yet to find a solution. I am saving sessions in a database.
My code is as follows:
// session
$_SESSION['userID'] = $user->id;
header('Location: /subdirectory/index.php');
Then at the top of index.php after the session_start(), i have var_dumped the $_SESSION global and the userID is not in there. As i said ive looked through the PHP manual (http://php.net/manual/en/function.session-write-close.php) and neither session_write_close or session_regenerate_id(true) worked for me.
Does anybody know a solution?
Edit: I have session_start() at the top of my file. When i var_dump the session global before the header redirect, i see the userID in there, but not in the other file, which is in a subdirectory of this script
I know this is an old toppic but I found the solution (for me).
I've put a exit after the header.
$_SESSION['session'] = 'this is a session';
header('location: apage.php');
exit;
This works for me
#Matt (not able to comment yet...): If:
a) It appears in the session before redirect
b) other keys work
80% of the time the problem is register_globals, and use of a equally named variable $userID somewhere (the other 19% is just overwriting in places one doesn't expect, 1% is unable to write/lock session before redirect and stale data, in which case you could try session_write_close() before the redirect). It goes without saying register_globals should be off :P
I haven't heard of this issue, but I haven't used sessions all that much.
With sessions you MUST do a few things and have a few setting setup:
cookies enabled on client side
session_start(), before anything happens
make sure you don't destroy the session(unless they want to logout)
The PHP session id must be the same (relates to cookies)
Another issue could be the $user->id is returning a reference to an object that doesn't exist on the next page. Most likely not, but make sure.
If I saw your code I could help you a lot more. But when debugging check the session key with session_id() and make sure it's the same. If you could try that then tell me I could keep helping.
I too would like to know how this ends up for when I get back into sessions.
You should start the session before using the session array.
PHP Code,
session_start();
$_SESSION['userID'] = $user->id;
header('Location: /subdirectory/index.php');
Have you got an session_start(); on the top?
Not tested but cant you do something like this:
session_start();
$_SESSION['userID'] = $user->id;
if( $_SESSION['userID'] == $user->id )
{
header('Location: /index.php');
}
I never have this Problem before, interesting
userID does not have any keyword status.
Only reason to me, is $_SESSION['userID'] is being overwritten or deleted somewhere.
Make sure you use session->start() in all the files you want to add/access the session.
One important thing ( which may not be applicable in your case ) is, if the session is being handled using cookie, cookie can be made to be accessible only under certain directory and subdirectories under that.
In your case anyhow, subdirectory will have access to the session.
Make sure both pages are the same php version
(php5, php4 sometimes have different session paths)
I had the same problem recently. I'm writting a customized MVC Website for school and, as everyone told, start_session() must be written in the very first lines of code.
My problem was THE LOCATION of "session_start()". It must be the first lines of your global controller, not the first lines of the view. $_SESSION was not accessible in controller's files because it was only initiated when the server render the view.
Then, I'm using session_write_close() after the header('location: xxx.php') call to keep session variables for the next request.
ex:
globalController.php :
//First line
session_start();
require_once('Model/Database.php');
require_once('Model/Shop/Client.php');
...
logonController.php:
...
//Users is validated and redirected.
$_SESSION['client'] = $client;
header('location: index.php');
session_write_close();
Hope it solved your problems.
This was annoying as hell but I finally figured out a solution.
config.php i had:
include 'session.php';
At the top of session.php, I had:
session_start();
By moving session_start() to the top of the config.php file, viola...
Problem solved!
Another option than killing your script forcefully with exit is to use session_write_close to force the changes to be written to the session store.
This should however not happen if your script is terminating correctly.
As the documentation about session_write_close states:
End the current session and store session data.
Session data is usually stored after your script terminated without
the need to call session_write_close(), but as session data is locked
to prevent concurrent writes only one script may operate on a session
at any time. When using framesets together with sessions you will
experience the frames loading one by one due to this locking. You can
reduce the time needed to load all the frames by ending the session as
soon as all changes to session variables are done.
In my case this only happened during debugging with Xdebug, when I triggered the same script multiple times and thus multiple process tried to manipulate the same session. Somehow the session could then no longer be unlocked.

Categories