简体   繁体   中英

regenerate_session_id destroying session information

I have an application that needs to create a new session id at specific times. Right now, this is causing the user to log out because $_SESSION ends up being empty.

It is my understanding that regenerate_session_id() should preserve the session information and just change the session id (meaning that $_SESSION['someVar'] would be available on subsequent requests.

What I'm finding is that $_SESSION is empty on subsequent requests.

I've tried copying the data:

$session = $_SESSION;
session_regenerate_id();
$_SESSION = $session;

but that didn't help. If I comment out session_regenerate_id(); subsequent pages load properly (the $_SESSION array is populated and the user stays logged in).

I have a dev environment that I just set up recently running a newer version of PHP (5.5) and this code is functioning as I would expect it to. I'm not aware of any other differences.

What am I missing? Thanks in advance.

session_start();

$_SESSION['name'] = "mike";

session_regenerate_id();

echo $_SESSION['name'];

outputs 'mike'

I did a little test on my server and it seems to be working fine.

<?php
session_start();
$old = session_id();
$_SESSION['name'] = "mike";
session_regenerate_id();
$new = session_id();
echo $_SESSION['name']."<br/>\n";
echo $old ."<br/>". $new
?>

Here is a sample of the output:

mike
d9oog3vo55936m3088o25qqe27
m6qq99pp1c80mit8e66ho3hfn3

As you can see, it is changing the session id and keeping the session variables in place, as it is supposed to. Perhaps your hosting provider has some funky settings in the php.ini? You might want to look into that.

Alternatively, and it is a bit of a hassle, couldn't you create a cookie with a key that will log them back in immediately after it logs them out, then delete the cookie?

After a good nights rest, it occurred to me that you probably have some header issues. Sessions are only valid within the same domain they are set in, so for example, if you set the session variable in www.example.com , then use a header redirect to header("location:example.com"); , your session variables will be blank, as they aren't set for that domain, they are set for www.example.com . I would check through your code and see if that is the issue, as you say, it is working fine in your sandbox.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM