Php-双向登录表单[管理员和用户]


Php - Two-Way Login Form [Admin & User]

我正在尝试制作一个登录表单,该表单能够检测用户是admin还是non-admin。我尝试了以下操作,但当我运行它时,没有得到任何结果:

<?php
    session_start();
    $message = "";
    if(count($_POST)>0)
    {
        $conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect("localhost", "prosoftl_rcc", "Royal"));
        ((bool)mysqli_query($conn, "USE prosoftl_rcc"));
        $result = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM student WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
        $row  = mysqli_fetch_array($result);
        $a = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM teacher WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
        $r = mysqli_fetch_array($a);
        if(is_array($row))
        {
            $_SESSION["id"] = $row[id];
            $_SESSION["name"] = $row[name];
        }
        elseif(is_array($r))
        {
            $_SESSION["admin"] = $row[id];
        }
        else
        {
            $message = "Invalid Username or Password!";
        }
    }
    if(isset($_SESSION["id"]))
    {
        header("Location:user_dashboard.php");
    }
    elseif(isset($_SESSION["admin"]))
    {
        header ("location:gui-admin.php");
    }
?>

当我为admin插入usernamepassword时,它会重新加载登录表单。

更新1:

非管理员部分工作正常,但管理员部分重定向/重新加载到登录表单。

您应该检查您的登录后表单,应该有这样的代码:

<form name="loginform" method="post" action="check.php">

如果您的"操作"vlaue无效,则页面可能会刷新。

您应该确认您的登录表单已发布到您发布的php页面。

试试这个,看看会发生什么。

session_start();
$msg = "";
if(count($_POST)>0){
 $conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect("localhost", "prosoftl_rcc", "Royal"));
    ((bool)mysqli_query($conn, "USE prosoftl_rcc"));
    $result = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM student WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
    $stdCount  = mysqli_num_rows($result);//counts the number or rows returned from student table
    $a = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM teacher WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
    $tchrCount = mysqli_num_rows($a);// same but with teachers table
    if($stdCount != 0){
       $row = mysql_fetch_array($result);
       $_SESSION['id'] = $row['id']; //set session for non admin.
   }else if($tchrCount != 0){
      $r = mysql_fetch_array($a);
      $_SESSION['admin'] = $r['id'];
  }else{
         echo "Username and Password is not Matching.";
  }
 }//end of the main if

我还没有测试过这个代码,所以不知道它是否有效,但我认为你已经掌握了逻辑。

  1. 使用引号:$row["id"]
  2. "位置:"必须是大写
  3. 调用"header"函数后,请确保使用"exit"

这段代码没有经过测试,但如果我理解正确,应该可以工作

<?php
    session_start();
    $message = "";
    if(count($_POST)>0)
    {
        $conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect("localhost", "prosoftl_rcc", "Royal"));
        ((bool)mysqli_query($conn, "USE prosoftl_rcc"));
        $result_student = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM student WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
        $row_student  = mysqli_fetch_array($result_student);
        $result_teacher = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM teacher WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
        $row_teacher = mysqli_fetch_array($result_teacher);
        if(is_array($result_student))
        {
            $_SESSION["id"] = $row_student["id"];
            $_SESSION["name"] = $row_student["name"];
            $_SESSION["admin"] = 0;
        }
        elseif(is_array($result_teacher))
        {
            $_SESSION["id"] = $row_teacher["id"];
            $_SESSION["name"] = $row_teacher["name"];
            $_SESSION["admin"] = $row_teacher["id"];
        }
        else
        {
            $message = "Invalid Username or Password!";
        }
    }
    if(isset($_SESSION["id"]))
    {
        if(@$_SESSION["admin"]>0)
        {  header ("Location: gui-admin.php");
           exit;
        }
        else
        {   header("Location: user_dashboard.php");
            exit;
        }
    }
?>

希望有帮助。。。。

但我能猜到为什么您的代码只为学生工作而面临这个问题。在这个-

if(is_array($row))

is_array($row)总是返回true,代码继续执行

$_SESSION["id"] = $row[id];
$_SESSION["name"] = $row[name];

但是$row[id]将是空的,因为没有与标准匹配的行,所以$_SESSION["id"]将不会被分配,并且当执行该操作时-

if(isset($_SESSION["id"]))
    {
        header("Location:user_dashboard.php");
    }
    elseif(isset($_SESSION["admin"]))
    {
        header ("location:gui-admin.php");
    }

不会执行任何if语句,因为没有设置它们。这是我的分析。这个could是错误的。

试试下面的解决方案-

您应该组合users表,以便查询用户是学生还是教师。然后根据主"用户"表查询学生表或教师表。向两个表查询相同的用户名和密码看起来不太好。

你可以将我代码中的元标记更改为头("Location:$url"),但我更喜欢这样,这样用户就不会缓存请求。希望它能有所帮助:-

$sql="SELECT * FROM {$table} WHERE username='{$username}' and password='{$password}'"; //My variables are already filtered and safe from SQL Injection. 
$result=mysqli_query($mysqli, $sql);
if(mysqli_num_rows($result))
{
    $fetch=mysqli_fetch_row($result);
    $_SESSION["id"]=$fetch['userid'];//Just fetching all details
    $_SESSION["Name"]=$fetch['name'];//and making session variables for that.
    $_SESSION["username"]=$fetch['username'];
    $isadmin=$fetch['isadmin']; //is a BOOL value in MySQL table.
        if($isadmin) //checking whether admin or not
        {
            $_SESSION["isadmin"]=1;
            echo "<meta http-equiv='refresh' content='0;url=adminurl'>";    } //if admin redirect to different url
        else{
            $_SESSION["isadmin"]=0;
            echo "<meta http-equiv='refresh' content='0;url=userurl'>";         
        }
}
else
{
    //Username Password Incorrect
    /* Show FORM HERE */
}

首先,您必须知道在SQL请求中直接使用POST数据确实是个坏主意,您必须避免这种情况,并使用mysqli_real_escape_string之类的函数清理数据。此外,您必须保护您的密码,并避免将其清楚地保存到数据库中,以便了解在数据库中存储密码的最佳方式。

对于您的两个SQL请求,您可以使用mysqli_multi_query,就像我在本例中所做的那样,我使用相同的脚本来获取POST数据并显示登录表单:

<?php
if(count($_POST) > 0){
    session_start();
    $link = mysqli_connect('localhost', 'user', 'pass', 'db');
    if(mysqli_connect_errno()) {
        die('db connection error : ' . mysqli_connect_error());
    }
    function secure_password($password){
        // secure your password here
        return $password;
    }
    // escape special characters
    $user_name = mysqli_real_escape_string($link, $_POST['user_name']);
    // you have to secure your passwords, when saving it of course
    $password = secure_password(mysqli_real_escape_string($link, $_POST['password']));
    $query  = "SELECT id FROM student WHERE name = '".$user_name."' and password = '".$password."';";
    $query .= "SELECT id FROM teacher WHERE name = '".$user_name."' and password = '".$password."'";
    $is_teacher = FALSE;
    if(count($_SESSION)) session_destroy();
    // you can use mysqli_multi_query for your two requests
    if (mysqli_multi_query($link, $query)) {
        do {
            if ($result = mysqli_store_result($link)) {
                if ($row = mysqli_fetch_row($result)) {
                    if($is_teacher){
                        $_SESSION['admin'] = $row[0];
                    } else {
                        $_SESSION['id'] = $row[0];
                        $_SESSION['name'] = $user_name;
                    }
                }
                mysqli_free_result($result);
            }
            if (mysqli_more_results($link)) {
                // if we have more results, so it's a teacher record
                $is_teacher = TRUE;
            }
        } while (mysqli_more_results($link) && mysqli_next_result($link));
    }
    mysqli_close($link);
    if(isset($_SESSION['id']))
    {
        header('Location:user_dashboard.php');
    }
    elseif(isset($_SESSION['admin']))
    {
        header('Location:gui-admin.php');
    }
    // no redirection, show the message and the login form
    echo 'Invalid Username or Password!';    
} 
?>
<form action='p.php' method='post'>
    User name : <input type='text' name='user_name'><br>
    Password : <input type='password' name='password'><br>
    <input type='submit' value='Submit'>
</form> 

希望这能有所帮助。