PHP 丢失会话的页面之间

PHP Losing Session's Between pages

所以我最近为我的所有用户创建了一个登录脚本和部分,显然允许他们登录到网站上的安全部分以查看某些内容。一旦我检查了所有变量是否正确并且用户输入了正确的详细信息,我就设置了两个会话。一个会话保存用户的 ID,另一个保存他们登录的时间。

然后该页面将重定向到一个名为 home.php 的页面,这样用户登录后就有了自己的小主页。但是重定向最终起作用了,但作为对另一个页面的测试,我所做的就是开始会话,然后回显这两个会话。

每次它们都是空的,这意味着会话不会从一页转移到另一页。我不知道为什么,我只是看不出出了什么问题。所以我的问题是,任何人都可以看到我哪里出错了。我已经过检查以确保我使用的是正确的版本并且我的主机支持它并且一切都恢复正常,所以我不知道......请帮忙! :)

<?php

//Session 
session_start();


require 'conn.php';


//If the POST var "login" exists (our submit button), then we can
//assume that the user has submitted the login form.
if(isset($_POST['login'])) {

//Retrieve the field values from our login form.
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$passwordAttempt = !empty($_POST['password']) ? trim($_POST['password']) : null;

//Retrieve the user account information for the given username.
$sql = "SELECT id, username, password FROM users WHERE username = :username";
$stmt = $pdo->prepare($sql);

//Bind value.
$stmt->bindValue(':username', $username);

//Execute.
$stmt->execute();

//Fetch row.
$user = $stmt->fetch(PDO::FETCH_ASSOC);

//If $row is FALSE.
if($user === false){
    //Could not find a user with that username!
    //PS: You might want to handle this error in a more user-friendly manner!
    die('Incorrect username / password combination!');
} else {
    //User account found. Check to see if the given password matches the
    //password hash that we stored in our users table.

    //Compare the passwords.
    $validPassword = password_verify($passwordAttempt, $user['password']);

    //If $validPassword is TRUE, the login has been successful.
    if($validPassword){

        //Provide the user with a login session.
        $_SESSION["user_id"] = $user['id'];
        $_SESSION["logged_in"] = time();

        echo " Display Errors: ".ini_set('display_errors', 1); 
        echo " Display Startup Errors: ".ini_set('display_startup_errors', 1); 
        echo " Error Reporting: ".error_reporting(E_ALL);

        //echo "<script type='text/javascript'>window.top.location='home.php';</script>";
        //exit;

        //Redirect to our protected page, which we called home.php
        ?>
            <!--<script type="text/javascript">
                alert("Login successful!");
                window.location.href = "home.php";
            </script>-->
        <?php
        exit;

    } else{
        //$validPassword was FALSE. Passwords do not match.
        die('Incorrect username / password combination!');
    }
}

}

?>
<!DOCTYPE html>
<html>
    <head>
    <!-- Basic Page Needs
    –––––––––––––––––––––––––––––––––––––––––––––––––– -->
    <meta charset="utf8">
    <title>Login</title>
    <meta name="description" content="Service Department User Registration Details">
    <meta name="author" content="Ben Smith">

    <!-- Mobile Specific Metas
    –––––––––––––––––––––––––––––––––––––––––––––––––– -->
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- FONT
    –––––––––––––––––––––––––––––––––––––––––––––––––– -->
    <link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">

    <!-- CSS
    –––––––––––––––––––––––––––––––––––––––––––––––––– -->
    <link rel="stylesheet" href="../css/normalize.css">
    <link rel="stylesheet" href="../css/skeleton.css">

    <!-- Favicon
    –––––––––––––––––––––––––––––––––––––––––––––––––– -->
    <link rel="icon" type="image/png" href="../images/favicon.png">

</head>
<body>
    <div class="container">
        <div class="row">
            <h1>Login</h1>

            <form method="post" action="login.php">
              <div class="row">
                <div class="six columns">
                  <label for="username">Username</label>
                  <input class="u-full-width" type="text" name="username" id="username">
                </div>
                <div class="six columns">
                  <label for="password">Password</label>
                  <input class="u-full-width" type="password" id="password" name="password">
                </div>
              </div>

              <input class="button-primary" type="submit" name="login" value="Login"></button>
            </form>

        </div>
    </div>



</body>

原来我有

//Provide the user with a login session. 
$_SESSION['user_id'] = $user['id']; 
$_SESSION['logged_in'] = time(); 
//Redirect to our protected page, which we called home.php 
header('Location: home.php'); 
exit; 

一旦到达脚本的那部分,页面就会重新加载。因此,它不会转到 home.php,而是会刷新 login.php,然后屏幕会变成空白(显然是因为屏幕上没有打印任何内容)

报错 当我将以下代码放入

ini_set('display_errors', 1); ini_set('display_startup_errors', 1); 
error_reporting(E_ALL);

结果我一无所获

这是重定向的典型问题。

您需要在重定向之前关闭您的会话,以便它被保存。

session_write_close();
header('Location: home.php'); 
exit; 

update: PHP 在脚本末尾自动保存会话。但如果脚本以 exitdie 结尾(这在重定向中很常见),它就不会这样做。另请参阅此答案:

更新 2:另见:http://php.net/manual/en/function.session-write-close.php#63970

我不确定最新的 PHP 版本是否仍然无法在突然退出时保存会话。

删除第一个 exit;,这将停止进一步执行。

旁注:我将其作为社区 Wiki 发布,因为它已在评论中得到解决。