问题
When a user logs in on our website, I want to change the session ID but keep whatever data is in the session. I want to do this for two reasons:
- To prevent a user account to be used at multiple places simultaneously (because if two people are using the same account, the actions of one will undermine the actions of the other).
- To let the user continue what he/she was doing on another computer (e.g moving from home computer to work).
These might seem contradictory, but really aren't if you think it through.
The problem is as follows; to get to the data that is currently in the session, I have to call session_start()
. This means I cannot call session_id()
afterwards to set a new session ID. Any ideas how to transfer the session data and change the session ID.
Update: I need to be able to choose the session ID myself. session_regenerate_id()
therefore won't work.
回答1:
You might be able to use session_regenerate_id():
<?php session_start(); $old_sessionid = session_id(); session_regenerate_id(); $new_sessionid = session_id(); echo "Old Session: $old_sessionid<br />"; echo "New Session: $new_sessionid<br />"; print_r($_SESSION); ?>
or even a cruder approach might work:
// save the session
session_start();
$session = array();
foreach ($_SESSION as $k => $v) {
$session[$k] = $v;
}
session_commit();
// create new session and copy variables
session_id("new session id");
session_start();
foreach ($session as $k => $v) {
$_SESSION[$k] = $v;
}
回答2:
Use this. Put it to a function:
function update_session($newsessid = '') {
// Backup the current session
$session_backup = $_SESSION;
// Set current session to expire in 1 minute
$_SESSION['OBSOLETE'] = true;
$_SESSION['EXPIRES'] = time() + 60;
// Close the current session
session_write_close();
// Set a new session id and start the session
$newSession = session_id($newsessid);
session_start();
// Restore the previous session backup
$_SESSION = $session_backup;
// Clean up
unset($session_backup);
unset($_SESSION['OBSOLETE']);
unset($_SESSION['EXPIRES']);
}
You would then call it when required:
update_session($customid);
回答3:
Or, you may just be able to use something like this:
$path=session_save_path();
$whatever_session_id;
pass these variables to the next page:
session_id()=$whatever_session_id;
session_save_path()=$path;
You'd be setting the path of the new session id to the old session data.... I don't know if this is really what you'd want, be here it is.
来源:https://stackoverflow.com/questions/1780852/change-session-id-and-keep-data