真正破坏 PHP 会话? [英] Truly destroying a PHP Session?
问题描述
我听到了关于这个主题的不同反应,那么销毁 PHP 会话的可靠方法是什么?
I have heard mixed responses on this topic, so what is a sure fire way to destroy a PHP session?
session_start();
if(isset($_SESSION['foo'])) {
unset($_SESSION['foo'];
...
}
session_destroy();
在最简单的情况下,这是否足以真正终止用户和服务器之间的会话?
In the most simple of cases, would this sufficient to truly terminate the session between the user and the server?
推荐答案
要销毁会话,您应该执行以下步骤:
To destroy a session you should take the following steps:
- 删除会话数据
- 使会话 ID 无效
为此,我会使用它:
session_start();
// resets the session data for the rest of the runtime
$_SESSION = array();
// sends as Set-Cookie to invalidate the session cookie
if (isset($_COOKIE[session_name()])) {
$params = session_get_cookie_params();
setcookie(session_name(), '', 1, $params['path'], $params['domain'], $params['secure'], isset($params['httponly']));
}
session_destroy();
为了确保会话 ID 无效,您应该只允许由脚本启动的会话 ID.所以设置一个标志并检查它是否设置:
And to be sure that the session ID is invalid, you should only allow session IDs that were being initiated by your script. So set a flag and check if it is set:
session_start();
if (!isset($_SESSION['CREATED'])) {
// invalidate old session data and ID
session_regenerate_id(true);
$_SESSION['CREATED'] = time();
}
此外,您可以使用此时间戳定期交换会话 ID 以减少其生命周期:
Additionally, you can use this timestamp to swap the session ID periodically to reduce its lifetime:
if (time() - $_SESSION['CREATED'] > ini_get('session.gc_maxlifetime')) {
session_regenerate_id(true);
$_SESSION['CREATED'] = time();
}
这篇关于真正破坏 PHP 会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!