簡體   English   中英

從登錄腳本困境重定向循環

[英]Redirect loop from login script dilemma

我遇到過一個我從未見過的登錄腳本問題,需要一些幫助來解決它。

我有以下php文件:

  1. 的index.php
  2. signIn.php

index.php中 ,存在一個登錄表單,該登錄表單指向signIn.php以驗證用戶信息。 只要用戶的憑據正確,它就會將用戶重定向回index.php並回顯用戶username

問題1

如果用戶未登錄,則應該回顯用戶名的index.php部分顯示以下錯誤:

未定義的索引:第26行的index.php中的用戶名

為了解決這個問題,我將以下PHP添加到index.php中 - 假設它有助於找到未定義的索引:

include 'signIn.php';

問題2

包含會導致重定向循環,並且不允許用戶登錄。當用戶登錄時還使用include signIn.php時,如何重定向回index.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 super global來獲取用戶名的值,就像使用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 ... 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM