用户认证 Session 一开始就设置

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';
?>

我的logout.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() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, session_start() has to be called.

In order to kill the session altogether, like to log the user out, the session id must also be unset. If a cookie is used to propagate the session id (default behavior), then the session cookie must be deleted. setcookie() may be used for that.

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

因此,您也可以在重定向之前在登录时重新生成会话 ID。啊,在通过 "header()".

重定向 "Location:" 之后使用 "exit;" 总是一个好主意
session_start();
session_regenerate_id(true);