用户身份验证会话从一开始就设置


User authentication Session is set from the start

我正在研究页面身份验证。它已经可以登录,但如果有人尝试通过 URL 访问页面,我希望它也在其他页面上进行用户身份验证。如果此人不是登录用户,请将该用户重定向到登录页面。我尝试了使用会话,但它不起作用。我遵循 MVC 结构不知何故,会话永远不会取消设置。我不知道为什么。。

这是我是如何做到的

我的登录控制器

    <?php
//LoginController
if($_POST)
{
    if(isset($_POST['submit']) AND $_POST['submit'] == "login")
    {
        $username = $_POST['username'];
        $password = $_POST['password'];
        try
        {
            include '../model/Login.php';
            $login = new Login($db, $username, $password);
            if($login == TRUE)
            {
                session_start();
                $_SESSION['username'] = $username;
                header("Location:../index.php");
            }
        }
        catch (Exception $exc)
        {
            echo $exc->getMessage();
        }
    }
}

我的索引控制器(用于主页)

<?php
include 'model/Database.php';
session_start();
//Checks if the user is logged in.
if(!isset($_SESSION['username'])) {
//echo"<h2>You have no access to this page!";
    include 'view/login.php';
    die();
}
include 'c:/wamp/www/mvc/model/Display.php';
$displayPatients = new Display($db);
$dataDisplay = $displayPatients->getData();
include 'view/Main.php';
?>

我的注销.php:当用户单击此按钮时:

<?php
//Logout
//destroys the session when the user clicks logout
session_destroy();
header('Location:view/login.php'); //redirect to the login

用户确实被注销重定向到登录页面,但仍设置了会话。会议从一开始就设置好了,我不知道为什么..

刚刚从 session_destroy() 的手册中取出

session_destroy() 销毁与当前关联的所有数据 会期。它不会取消设置任何与 会话,或取消设置会话 Cookie。使用会话变量 同样,必须调用 session_start()。

为了完全杀死会话,例如将用户注销, 还必须取消设置会话 ID。如果使用 cookie 来传播 会话 ID(默认行为),则会话 Cookie 必须 删除。setcookie() 可以用于此目的。

所以在我看来,您需要在启动新会话时销毁您的会话 ID 或将其设置为其他内容,否则您的下一个 sesson_start() 会再次恢复旧会话。

因此,您也可以在重定向之前在登录时重新生成会话 ID。啊,在"位置:"通过"header()"重定向后使用"exit;"总是一个好主意。

session_start();
session_regenerate_id(true);