PHP Session Variables not saving after redirect? - php

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

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 not working for first time, from second time it works

I don't know what is the problem. When I do login for first time after deleting all history and cookies and cache, it doesn't set session to redirected page. But when I do login for second time, session is set to redirected page. Here id the code of First & second page.
First Page
<?php
session_start();
include('includes/connection.php');
$email=$_POST['email'];
$password=$_POST['password'];
$data=mysqli_query($GLOBALS["___mysqli_ston"], "select * from user_registration where email='$email' and password='$password' ");
$data1=mysqli_num_rows($data);
$val=mysqli_fetch_array($data);
if($data1>0)
{
$_SESSION['user_id']=$val['user_id'];
echo "<script>window.location.href='index.php'</script>";
}
else
{
echo "<script>window.location.href='login.php'</script>";
}
?>
Second Page
<?php
session_start();
$val=$_SESSION['user_id'];
echo $val;
?>
session_start(); should be at the very top of both scripts!
Session variables are saved on server and assigned a unique code that are passed to browser in cookies.
Because the cookies are set by the headers they need to be sent before anything else!
Even a whitespace at the top of your script may cause session cookie to be not properly set on browser side.
So always start the both scripts like this:
<?php
session_start();
// Rest of the code....
It looks like they are on top on your question but I think you edited question later to put there.
That's the only reason sessions are not working the first time and they are working on second time.
instead of the echo use
header("Location: index.php");
EDIT
alsosession_start should be declared at the top of the first page because you cant set a session that doesn't exist in the context if you were running it in a console environment you would receive the following error
"$_SESSION['user_id'] does not exist in the current context"
same happening here. is php 5.6 is super strange problem. on some pages work normaly and on one dont. First request is like dont get recognized.. :)
for example: set
#when page load set:
$_SESSION['a']=0;
#then with JS requests increase $_SESSION['a']+=1; and this start working on third request...

PHP Session-Based flash message

I'm trying to create a Session-Based flash message in PHP:
In register.php page, I set the session as follow:
$_SESSION['flash'] = 'Registered';
Then, after redirecting user to the home page, I printed the flash message:
if (isset($_SESSION['flash'])) {
echo $_SESSION['flash'];
unset($_SESSION['flash']);
}
The session is started in both pages.
The problem is:
I get the flash message in the home page only if I remove the unset function, and then the message is always printed.
I wrote a library just for this type of issues: https://github.com/tamtamchik/simple-flash.
Once you have it installed you can do this:
// put message not session
flash('Some error message', 'error');
// print it after redirect
echo flash()->display();
It'll generate Bootstrap friendly alert messages.
I just solved my problem by adding exit after redirecting user to escape the execution of the register page, so the session won't be unset in the current page before using it in the next page.
Please note that session_unset just clears out the sesison for usage. The session is still on the users computer. Note that by using session_unset, the variable still exists.
Using session_unset in tandem with session_destroy however, is a much more effective means of actually clearing out data. As stated in the example above, this works very well, cross browser:
<?php
session_unset();
session_destroy();
?>

$_SERVER['HTTP_REFERER'] The page isn't redirecting properly PHP

I am using header('Location: ' . $_SERVER['HTTP_REFERER']); on Logout.php page and it is working properly there.But when I have used it on Login page it gives me error "The page isn't redirecting properly PHP" and "Firefox has detected that the server is redirecting the request for this address in a way that will never complete."
My code is :
if($resT==3){
$_SESSION['userId'] = $_POST["user"];
header('Location: '.$_SERVER['HTTP_REFERER']);
}
$resT is the usertype I am getting from database according to the user.
This error generally comes when you have loop cycle on the page, means you are redirecting in a cycle that is will not halt. There is some logical error in your page.
HTTP_REFERER Will redirect you to the base address e.g http://localhost/
Therefore check your redirection on the pages where you throw the user.
HTTP_REFERER is set by client and thus not guaranteed to be available. So, it cannot be used for the any purpose other than logging.
Store initial location in a session or pass it via form parameter.
Hi Its better to set your back page to be into session and redirect user to that page.
Like $_SESSION['backfromlogin'] = $currentpage; than use this session variable to redirect back.
your issue is, referrer redirecting to the login page itself. you can echo referrer to make sure.

Sometimes Session variables stop working

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.

Categories