【问题标题】:PHP Losing Session's Between pagesPHP在页面之间丢失会话
【发布时间】:2019-04-04 15:38:59
【问题描述】:

所以我最近为我的所有用户创建了一个登录脚本和部分,显然允许他们登录到网站上的安全部分以查看某些内容。一旦我检查所有变量都正确并且用户输入了正确的详细信息,我设置了两个会话。一个会话保存用户的 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);

结果我一无所获

【问题讨论】:

    标签: php mysql session session-variables


    【解决方案1】:

    这是一个典型的重定向问题。

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

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

    update:PHP 在脚本结束时自动保存会话。但如果脚本以exitdie 结尾(这在重定向中很常见),则不会这样做。另请参阅此答案: https://stackoverflow.com/a/14870204/358813

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

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

    【讨论】:

    • 这不会丢失我存储在会话中的数据吗?
    • 我不确定它是否是一个“经典问题”,我从来不需要在任何地方使用它来保存会话......
    • 很奇怪,我刚刚阅读了 Joel 的关于声誉系统的帖子和 Jeff 的关于 downvoting 和我无缘无故被否决后几分钟的帖子 :)
    • 关于您的编辑:刚刚测试过,但事实并非如此,会话仍然使用退出保存
    • 我所说的行为已经存在很长时间了。它可能随着 PHP 的新版本而改变,坦率地说我不知道​​。
    【解决方案2】:

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

    旁注:我将其作为社区 wiki 发布,因为它已在 cmets 中解决。

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 2012-06-15
      • 1970-01-01
      • 2023-03-30
      • 2011-12-15
      • 2016-03-17
      • 2014-08-14
      相关资源
      最近更新 更多