繁体   English   中英

会话无效

[英]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来获取您的index.phplogin page中的值。

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

暂无
暂无

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

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