从登录脚本困境重定向循环

Redirect loop from login script dilemma

我遇到了一个以前从未见过的登录脚本问题,需要一些帮助来解决它。

我有以下 php 个文件:

  1. index.php
  2. signIn.php

index.php中,有一个登录表单指向signIn.php以验证用户信息。只要用户的凭据正确,它就会将用户重定向回 index.php 并回显用户 username.

问题 1

如果用户未登录,index.php 中应该回显用户名的部分会显示以下错误:

Undefined index: username in index.php on line 26

为了解决这个问题,我将以下 PHP 添加到 index.php - 假设它有助于找到未定义的索引:

包括'signIn.php';

问题2

包含会导致重定向循环,并且不允许用户登录。如何在用户登录时重定向回 index.php使用包括 signIn.php?


index.php(精简)

<?php
    session_start();
    include 'signIn.php';
?>
<head>
    Blah blah
</head>
<body>
    <div>
        <?php
            if($_SESSION["username"]) {
                echo $_SESSION["username"];
            } else {
                echo "Guest";
            }
        ?>
    </div>
    <form action="signIn.php" method="POST">
        <h1>Sign in</h1>
        <?php if($message!="") { echo $message; } ?>
        <input type="email" name="username">
        <input type="password" name="password">
        <input type="submit" value="Sign in">
    </form>
</body>

signIn.php

<?php
    session_start();
    $message="";
    if(count($_POST)>0) {

        $conn = mysql_connect("localhost","blah","blah");
        mysql_select_db("blah",$conn);

        $result = mysql_query("SELECT * FROM users WHERE UserName='" . $_POST["username"] . "' and Password = '". $_POST["password"]."'");

        $row  = mysql_fetch_array($result);

        if(is_array($row)) {
            $_SESSION["username"] = $row["UserName"];
        } else {
            $message = "Invalid Username or Password!";
        }
    }

    if(isset($_SESSION["username"])) {
        header("Location:index.php");
    }
?>

您需要检查 $_SESSION['username'] 是否已设置:

if (isset($_SESSION['username']) {
    // Hi user!
}

而对于问题 2,如果与上述条件相反,您只想包括 signIn

if (! isset($_SESSION['username']) {
    // Redirect the user
}

您需要使用 $_POST 超级全局来获取用户名的值,就像您使用 post 方法一样。

像这样,

  $_SESSION["username"] = $_POST["username"];

index.php

if (!isset($_SESSION['username'])) {
   Header("Location: signin.php");
   exit(0);
}

signin.php

<?php
    session_start();

    if(count($_POST)>0) {
           // do auth here
           ## Beware of your mysql code which is sensible to sql injection.
           //
           if ($AUTHOK) {
               header("Location:index.php");
               exit(0);
           }
    }

?>
... html code ...