PHP 如何在离开页面后完全销毁会话

PHP How to completely destroy a session after leave the page

我想制作一个简单的 PHP 页面,您只有先登录才能访问该页面。我的代码是这样的:

if (the user logged in correctly) {

session_start();
  echo "THE HTML PAGE. (I did this in echo because I only want to show it for the logged in users.)";

} else {
    header ("Location: index.html");
    die();
    session_destroy();
}

所以我的目标是,当用户点击“返回页面”按钮时,会话被销毁,只有在登录后才开始一个新的。但是现在,如果用户点击“返回”返回页面”按钮,而不是单击“继续页面”按钮。它说,文档已过期。很酷,但是如果我刷新页面,我可以在不登录的情况下访问该页面。

    if(isset($_SESSION['email']) && isset($_SESSION['id']))
    {
        return true;
    }
    else 
    {
        return false;
    }

//然后在头文件中调用该函数进行校验。

这是一个解决方案



// put on top of every page
session_start();


function is_logged_in(): bool
{
    if (isset($_SESSION['email']) && isset($_SESSION['id']) && isset($_SESSION['is_logged_in'])) {
        return true;
    } else {
        return false;
    }
}
function is_auth()
{
    if (!is_logged_in()) {  
       session_destroy(); // change happend here
       header("Location: index.html");
       die();
    }
}

is_auth();

//  add your code here
header ("Location: index.html");
die();
session_destroy();

关于会话销毁,你不能那样做。见下文:

首先你需要销毁会话。 然后你需要重定向用户。

正确:

session_destroy();
header ("Location: index.html");
die();

有时 unset 函数也可以看到 unset 和 destroy 是两个单独的函数, unset 对于取消设置某些值(例如电子邮件、id、名称等)很有用,并且 destroy 会完全破坏会话,因此请确保销毁会话,您再次不需要该会话,因此请尝试使用 unset().