简体   繁体   中英

session_regenerate_id is not creating a new session id

I have a script which is meant to finish the current session and start a new one. There is a segment of code I use and it works fine on my development computer. However, when I posted it to the production server, the session id is constantly remaining the same.

The following is my code for restarting the session:

session_start();

$_SESSION = array();
$_POST = array();
$_GET = array();

if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), 
              '', 
              time() - 42000,
              $params["path"], 
              $params["domain"],
              $params["secure"], 
              $params["httponly"]
    );
}
session_destroy();
session_write_close();
session_start();    

session_regenerate_id(true);

On the last line, a new session id is not generated.

Why would this be different between two servers running PHP? And what can I do to correct it?

After some experimenting I solved the problem.

The session_regenerate_id(true) line does not regenerate a new session id if any text has been written into the response. I already had a series of echo statements issuing text for debugging purposes and after I removed them new session ids were created.

session_regenerate_id() updates the current session id with a newly generated one. It does not change session variables.

echo session_id();
session_regenerate_id();
echo session_id(); 

You should unset session to do that:

unset($_SESSION); // or
$_SESSION = array();

How to start a new session:

session_start();
session_destroy();
session_regenerate_id();
unset($_SESSION);
session_start();

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