简体   繁体   English

屏幕之间的PHP会话不持久

[英]PHP session not persisting between screens

I have come across an issue that has confused me a lot. 我遇到了一个让我很困惑的问题。 I am working on a login screen using PHP and MySQL. 我正在使用PHP和MySQL在登录屏幕上工作。 I manage to validate the username and password against an existing user in the database and after this, I initiate a session, and set the session variable username to the username provided in the login screen. 我设法针对数据库中的现有用户验证用户名和密码,然后启动会话,并将会话变量username设置为登录屏幕中提供的用户名。

    $username = html($_POST['username']);
    $password = html($_POST['password']);

    $result = $pdo->prepare('SELECT * FROM users WHERE username = :username  AND    password = :password');
    $result->bindValue(':username', $username);
    $result->bindValue(':password', $password);
    $result->execute();

    foreach($result as $user)
    {
        $count = $count + 1;
    }

    if ($count == 1)
    {
              session_start();
          $_SESSION['username'] = $username;
       ` //if I do an echo $_SESSION['username'] it displays the correct user
          header('Location: .');
          exit();`
    }

However when it transfers me to the index.php page the $_SESSION['username'] variable has disappeared and I do not understand why. 但是,当我将我转移到index.php页面时, $_SESSION['username']变量消失了,我也不明白为什么。 This is the code I use in index.php to check for the username: 这是我在index.php中使用的代码来检查用户名:

<p><a href="view.php">View all tasks</a></p>
<p><a href="form.php?add">Add your own task</a></p>

<p>Welcome, <?php echo $_SESSION['username']; ?></p>

however I get the following error: Notice: Undefined variable: _SESSION in C:\\xampp\\htdocs\\abcabcabc\\index.php on line 16 但是我得到以下错误: Notice: Undefined variable: _SESSION in C:\\xampp\\htdocs\\abcabcabc\\index.php on line 16

All advice will be greatly appreciated guys 所有建议将不胜感激的家伙

sesssion_start()添加到使用会话的所有脚本中

You must use session_start(); 您必须使用session_start(); at the beginning of index.php file. 在index.php文件的开头。

The first 2 answers are correct. 前两个答案是正确的。 You must start session on each page. 您必须在每个页面上启动会话。 I usually just put it in a file that is "included" in every page already (like a header file) so I don't have to think about it. 我通常只是将其放在已经“包含”在每个页面中的文件中(例如头文件),因此我不必考虑它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM