我正在测试PHP会话中安全检查的实现。我可以成功检测会话是否从另一个IP地址启动,我可以成功启动一个新会话。但是,来自旧会话的数据会被复制到新会话中!如何在保留其合法所有者的先前会话数据的同时启动空白会话?
这是我的代码到目前为止,经过多次尝试失败后:
<?php
// Security check
if( isset($_SESSION['ip_address']) && $_SERVER['REMOTE_ADDR']!=$_SESSION['ip_address'] ){
// Check failed: we'll start a brand new session
session_regenerate_id(FALSE);
$tmp = session_id();
session_write_close();
unset($_SESSION);
session_id($tmp);
session_start();
}
// First time here
if( !isset($_SESSION['ip_address']) ){
$_SESSION['ip_address'] = $_SERVER['REMOTE_ADDR'];
$_SESSION['start_date'] = new DateTime;
}
关于会话的官方文档非常令人困惑:(
更新:我发布了一些经过反复试验的调查结果。他们似乎工作:
<?php
// Load the session that we will eventually discard
session_start();
// We can only generate a new ID from an open session
session_regenerate_id();
// We store the ID because it gets lost when closing the session
$tmp = session_id();
// Close session (doesn't destroy data: $_SESSION and file remains)
session_destroy();
// Set new ID for the next session
session_id($tmp);
unset($tmp);
// Start session (uses new ID, removes values from $_SESSION and loads the new ones if applicable)
session_start();
答案 0 :(得分:7)
只需在session_unset
之后致电session_regenerate_id
即可为当前会话重置$_SESSION
:
if (isset($_SESSION['ip_address']) && $_SERVER['REMOTE_ADDR']!=$_SESSION['ip_address']) {
// Check failed: we'll start a brand new session
session_regenerate_id(FALSE);
session_unset();
}
答案 1 :(得分:2)
当新用户连接到您的服务器时,该脚本应该只能访问该用户的会话变量。您将希望将其他信息存储在散列会话变量中,以验证会话是否未被置位。如果它被顶起,没有理由开始一个新的会话,可能只是退出脚本并发出警告。
这里有很多人用来指纹会话的功能:
function fingerprint() {
$fingerprint = $server_secure_word;
$fingerprint .= $_SERVER['HTTP_USER_AGENT'];
$blocks = explode('.', $_SERVER['REMOTE_ADDR']);
for ($i=0; $i<$ip_blocks; $i++) {
$fingerprint .= $blocks[$i] . '.';
}
return md5($fingerprint);
}
答案 2 :(得分:1)
使用此
unset($_SESSION['ip_address'])
而不是'unset($ _ session)' 您也可以使用session_destroy。
答案 3 :(得分:0)
highway=secondary
将销毁会话数据。例如,
session_destroy
将输出
session_start();
$_SESSION["test"] = "test";
session_write_close();
session_start();
// now session is write to the session file
// call session_destroy() will destroy all session data in the file.
session_destroy();
// However the you can still access to $_SESSION here
print_r($_SESSION);
// But once you start the session again
session_start();
// all session data is gone as the session file is now empty
print_r($_SESSION);