在 PHP 中从会话注销的正确方法

2022-08-30 12:36:25

我已经阅读了许多用于注销脚本的php教程,我想知道从会话中注销的正确方法是什么!

脚本 1

<?php
session_start();
session_destroy();
header("location:index.php");
?>

脚本 2

<?php
session_start();
session_unset();
session_destroy();
header("location:index.php");
?>

脚本 3

<?php
session_start();
if (isset($_SESSION['username']))
{
    unset($_SESSION['username']);
}
header("location:index.php");
?>

有没有更有效的方法来做到这一点??会话总是可以通过重新登录来创建的,所以我应该为使用session_destroy()而使用unset($_SESSION['variable'])而烦恼吗?以上3种脚本中哪一种更可取?


答案 1

PHP 手册的 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();
?>

答案 2

就个人而言,我做以下工作:

session_start();
setcookie(session_name(), '', 100);
session_unset();
session_destroy();
$_SESSION = array();

这样,它将杀死cookie,销毁内部存储的所有数据,并销毁会话信息的当前实例(被忽略)。session_destroy


推荐