PHP session values lost after redirect on one script but preserved after redirection on another
On my registration script i have:
// Save registration information into the database
// Set sessions
$_SESSION['var1'] = 'somevalue';
$_SESSION['var2'] = 'anothervalue';
header('Location: /somewhere');
exit();
Then on my login script i have:
// Check if user provided correct login credentials
if (correct) {
$_SESSION['var1'] = 'somevalue';
$_SESSION['var2'] 开发者_如何学运维= 'anothervalue';
}
header('Location: /somewhere');
exit();
What happened is that the session variables were lost after the header redirect in the registration script but they were preserved after the redirect in the login script.
I've checked session_id()
at both pages and they have the same value, included session_start()
at the top of every page and basically tried the solutions to this common problem found on Stackoverflow but somehow nothing seemed to work.
I'm beginning to wonder if it is something to do with my server configuration instead of my code.
Are you redirecting between www.example.com and example.com? Since those are two different domains.
The manual page about session_write_close has comments from lots of people with this or similar problems. Some say it's fixed by calling session_write_close before the "header('location" line.
This post: http://us.php.net/manual/en/function.session-write-close.php#86791
He says that didn't work for him, but calling session_regenerate_id() did work. (This changes the session cookie, and forces php to send the cookie out.
Sending the cookie again may be required. I've read people saying that some browsers don't send cookies after a redirect, except cookies they just got at the original url.
I realize this is an old thread but I just moved a site to a new dedicated IP with a certificate and the sessions would not pass on a header("location:") redirect... where at the old location they were passing just fine. The only thing that worked was adding session_regenerate_id(true); before the redirect. I'm still curious as to why? Any ideas out there?
I had the same problem, after that I have tried everything:
exit();
session_write_close();
either $_SESSION['user'] = $user;
or session_register("user");
all possibile geometrical positions in page of session_start();
at the end... I found that in my configuration the folder of the save path of the session was not writable.
Once set to writable and set the correct user, everything worked like a charm.
To find your save path, look in your phpinfo() what is under session.save_path
why use exit()? header("location: /somewhere"); will prevent the remainder of the script to be executed.
精彩评论