会话获胜';不起作用


Session won't work

我对已登录用户的会话有问题,它总是显示为用户未登录。

index.php

<?php
session_start();
if (!isset($_SESSION['email'])) {
    if (isset($_POST['email']) && isset($_POST['pass'])) {
        $email  = mysqli_real_escape_string($con, $_POST['email']);
        $pass   = mysqli_real_escape_string($con, $_POST['pass']);
        $sqli   = "SELECT * FROM users WHERE email='$email' AND pass='$pass' LIMIT 1";
        $result = mysqli_query($con, $sqli);
        if ($result && mysqli_num_rows($result) == 1) {
            while ($row = mysqli_fetch_array($result)) {
                $id = $row['id'];
                header("Location: home.php?=$id");
                exit();
            }
        }
    }
} else {
    header("Location: home.php");
}
?>
<form action="index.php" method="POST">
    <input name="email" type="text"/>
    <input name="pass" type="password"/>
    <input type="submit" name="submit" value="Submit">
</form>

home.php有:

<?php
session_start();
if (!isset($_SESSION['email'])) {
    header("Location: index.php");
} else {
    echo "welcome";
}
?>

现在,当我登录时,我可以访问home.php,但在那之后,home.php将我重定向回index.php,就像会话从未开始一样。。。

请参阅底部代码中的注释。您忘记在POST之后设置会话,并且不需要while循环:

<?php
session_start();
if (!isset($_SESSION['email'])) {
    if (isset($_POST['email']) && isset($_POST['pass'])) {
        $email  = mysqli_real_escape_string($con, $_POST['email']);
        $pass   = mysqli_real_escape_string($con, $_POST['pass']);
        $sqli   = "SELECT * FROM users WHERE email='$email' AND pass='$pass' LIMIT 1";
        $result = mysqli_query($con, $sqli);
        if ($result && mysqli_num_rows($result) == 1) {
            /* Authenticated User */
            /* Since you are getting only one row, you don't need a `while` loop. */
            $row = mysqli_fetch_array($result);
            $id = $row['id'];
            /* Actually set the session variable. */
            $_SESSION["email"] = $id;
            header("Location: home.php?=$id");
            exit();
        }
    }
} else {
    header("Location: home.php");
}
?>

注意:

  1. 您需要设置$_SESSION
  2. 使用哈希密码以提高安全性

您只检查会话是否存在,您需要设置会话数组的值。

$_SESSION['value'] = 'Item';

然后检索

echo $_SESSION['value']

希望能有所帮助。

在成功登录后前往home.php之前,您需要设置一个SESSION,以获取login page中的值(在您的情况下为index.php)。

在登录页面(index.php)中,在header("Location: home.php?=$id");之前添加$_SESSION['email'] = $id