会话变量没有更新,不知道为什么

问题描述 投票:0回答:0

我正在使用 PHP 下的 PDO 创建登录系统。接受用户输入、检查数据库并返回详细信息是否匹配的系统工作正常。但是,在此过程结束时,我跟踪用户是否登录的会话变量没有按预期更新。

这是我的索引文件的内容:

<?php 
    namespace Website_Code;
    include("includes/weatherAPI.php");
    include("includes/header.php");
    session_start();

    if (!isset($_SESSION["isLoggedIn"])) {
        $_SESSION["isLoggedIn"] = false;      
        echo "session started";
    }

    if ($_SESSION["isLoggedIn"] == false) {
        echo "not logged in";
        header("Location: login.php");
    } 
?>

<!-- this content is not relevant to the question, but it's awkward to cut around it -->
<form class="row pt-2 px-2" role="search" method="post" action="">
    <div class="col-auto">
        <input class="form-control" type="search" placeholder="Search city...." aria-label="Search" name="city" id="city">
    </div>
    <div class="col-auto">
        <button class="btn btn-primary mb-3" type="submit" name="search">Search</button>
    </div>
</form>

<?php
    echo $html;
?>

<?php 
    include("includes/footer.php");
?>

索引文件在加载时创建一个会话并将“isLoggedIn”的默认值设置为 false。然后检查该值是否等于 false。如果是,它会重定向到 login.php 脚本,如下所示:

<?php 
    namespace Website_Code;
    use PDO;
    use PDOException;

    include("includes/header.php");
    include("user.php"); // this file contains the user class with a function that checks user login details
    session_start();

    if (isset($_POST["submitBtn"])) {
        $user = new User();
        $user->set_username($_POST["userInput"]);
        $response = $user->check_login();

        if ($response == true) {
            echo "Login successful";
            $_SESSION["isLoggedIn"] == true;
            echo "\n";
            var_dump($_SESSION["isLoggedIn"]);
            //echo "<script>window.location.replace('index.php');</script>";
        }
        else {
            echo "Login failed, please try again";
        }
    }
?>
    <form action = "<?php $_SERVER['PHP_SELF']; ?>" method="post">
        <div class="mb-3">
            <label for="userInput" class="form-label">Username</label>
            <input type="text" class="form-control" name="userInput">
        </div>
        <div class="mb-3">
            <label for="passwordInput" class="form-label">Password</label>
            <input type="password" class="form-control" name="passwordInput">
        </div>
        <button type="submit" name="submitBtn" class="btn btn-primary">Submit</button>
    </form>

<?php
    include("includes/footer.php");
?>

我已经注释掉了注入的JavaScript代码,因为从测试来看,会话变量“isLoggedIn”似乎没有更新,这意味着当Js执行时,index.php代码会看到它仍然等于false,然后回到 login.php 脚本。

任何帮助表示赞赏。

我试过在不同的地方声明会话,但我真的不知道该怎么做。

php pdo
© www.soinside.com 2019 - 2024. All rights reserved.