This is a very specific question regarding when exactly to call session_regenerate_id()
. Is there a difference or security risk between calling session_regenerate_id()
before or after setting a secure value in session.
Before setting a value:
if ($login_success) {
session_regenerate_id(true);
$_SESSION['login_status'] = 'logged_in';
}
Or after setting a value in session:
if ($login_success) {
$_SESSION['login_status'] = 'logged_in';
session_regenerate_id(true);
}
This is how it works, session_regenerate_id()
will create and change the session id, transferring the session to the new file and send out the cookie. Passing true
as an argument will also delete the old session file, omitting the argument will leave it.
So, whether you use
session_regenerate_id(true);
$_SESSION['login_status'] = 'logged_in';
or
$_SESSION['login_status'] = 'logged_in';
session_regenerate_id(true);
it is the same: info is rewritten to the new file and the cookie is sent out. I'd advise using true
as argument though at all times, to avoid old session hijacking.
They are effectively the same; session information is actually persisted only when calling session_write_close() (or implicitly when the script ends). So the data would not get persisted for the old id.