gpt4 book ai didi

php - 关闭 session 并开始新的 session

转载 作者:行者123 更新时间:2023-12-03 00:11:14 26 4
gpt4 key购买 nike

我正在我的 PHP session 中测试安全检查的实现。我可以成功检测 session 是否是从另一个 IP 地址启动的,并且我可以成功启动新 session 。但是,旧 session 中的数据会复制到新 session 中!如何启动空白 session ,同时为其合法所有者保留以前的 session 数据?

这是我迄今为止的代码,经过多次失败的尝试:

<?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;
}

关于 session 的官方文档非常困惑:(

更新:我正在发布一些通过反复试验得到的发现。它们似乎有效:

<?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();

最佳答案

只需调用 session_unset之后session_regenerate_id重置当前 session 的$_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();
}

关于php - 关闭 session 并开始新的 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4345014/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com