在session_destroy()之后保留会话变量?

时间:2013-08-01 11:06:01

标签: php session

我知道有一个相同的问题here,但是接受的答案说这是一个补丁的错误,但链接说不然。该链接表明它是预期的行为而不是错误。

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

$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'

3 个答案:

答案 0 :(得分:1)

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

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

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

而不是呼叫:

session_destroy();
session_start();

这将有效地为您清理会议。

答案 1 :(得分: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

答案 2 :(得分:1)

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

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
相关问题