在Session_destroy()之后保留会话变量


Preserving a Session Variable after session_destroy()?

我知道这里有一个相同的问题,但公认的答案说这是一个带有补丁的错误,但链接却不是这样说的。链接说这是故意的行为,而不是错误。

问题中的其他答案正是我试图做的

$variableToPreserve = $_SESSION['foo'];
session_destroy();
session_start();
// At this point in the debugger, all previous session variables are still 
// in the session anyway, making me think the session has not been destroyed yet.
$_SESSION['foo'] = $variableToPreserve;

下一个请求:

session_start();
// This line errors as 'foo' is not in the session.
$var = $_SESSION['foo'];

我唯一的猜测是,直到请求完成后,会话才真正被销毁。我可以保留它的唯一方法是保留所有会话变量,但实际上我需要销毁会话,并且只设置'foo'

会话是通过cookie处理的,所以(我想)这应该是预期的行为。

您可以手动取消设置会话变量中的所有值:

foreach ($_SESSION as $k => $v) {
    unset($_SESSION[$k]);
}

代替调用:

session_destroy();
session_start();

这将有效地为您清除会话。

我为您检查了代码,这就是我看到的行为。

session_start();
$_SESSION['foo'] = 1;
$variableToPreserve = $_SESSION['foo'];
session_destroy();
session_start();
// At this point, the session variable is indeed destroyed, as is evident from the error that the next line throws.
echo $_SESSION['foo'];
$_SESSION['foo'] = $variableToPreserve;
echo $_SESSION['foo'];
// The above line echoes 1

您的会话销毁代码与PHP手册提供的代码不同,例如:

http://php.net/manual/en/function.session-destroy.php

// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}
// Finally, destroy the session.
session_destroy();

您可以测试演示:http://phpfiddle.org/lite/code/2vi-r9a