正确登出网页的方法


Proper way to logout of webpages

我一直使用session_destroy()很长一段时间来结束用户的会话。但在深入研究之后,我意识到它只会破坏服务器端的会话数据。cookie仍将存储在客户端,这意味着浏览器将继续发送cookie,但会话id已不再有效。那么,退出会话的正确方法是什么呢?还需要在客户端删除cookie吗?

根据手册,还有更多的事情要做:

为了彻底终止会话,比如注销用户会话id也必须取消设置。如果使用cookie来传播会话id(默认行为),那么会话cookie必须是删除。Setcookie()可用于此。

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