使用password_verify()登录系统

问题描述 投票:1回答:1

我正在尝试使用哈希密码创建登录系统。应该发生的是,当我单击“提交”按钮后,应该创建一个会话,然后将我重定向到home.php。如果输入数据与数据库中的数据不匹配,我应该收到“错误1”或“错误2”警报。我的问题是,当我单击“提交”按钮时,所有发生的事情都是将我重定向到login.php。我没有错误也没有警报,只有黑屏,带有login.php URL。

我试图弄清楚如何使password_verify()部分起作用。任何帮助都将受到赞赏。

数据库图片:https://imgur.com/a/BXiHBN4尝试登录后发生的情况的图片:https://imgur.com/a/qKZ1tsi

表单代码:

<html>

<head>

<title> Login now! </title>

<meta charset="UTF-8">

<link rel="stylesheet" type="text/css" href="css/style.css"/>

</head>

<body>

<header>

  <div class="alignRight">
    <a href="registration.html"> Register </a> &nbsp; &nbsp;
  </div>

  <div class="alignLeft">
    <a href="contact.html"> Contact us </a> &nbsp; &nbsp; 
    <a href="aboutus.html"> About us </a> &nbsp; &nbsp;
    <a href="news.html"> News </a>
  </div>

</header>

<h1> Welcome back! </h1>

<h2> Log in to continue with your work. </h2> 

<form name="login-form" id="login-form" action="login.php" method="post">

    <input class="_40" type="text" name="username"  pattern="[a-zA-Z0-9_]{1,15}" 
placeholder="Username"  required /> 

    <br />

    <input class="_40" type="password" name="pwd"  placeholder="Password"  required />

    <br />

    <input id="loginSubmitButton" type="submit" value="Submit"  /> 

</form>

</body>

</html>

PHP代码:

<?php


session_start();

$servername ="localhost";
$username = "root";
$password = "";

$link = mysqli_connect($servername, $username, $password);

mysqli_select_db($link, "users");


$username = mysqli_real_escape_string($link, $_POST["username"]);
$pwd = mysqli_real_escape_string($link, $_POST["pwd"]); 
$query = "SELECT * FROM users WHERE Username = '$username'";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_assoc($result);

if(($result->num_rows > 0))
{
    while($row = mysqli_fetch_array($result))
    {
        if(password_verify($pwd, $row["Hash"]))
        {
            $_SESSION["username"] = $username;
            header("location:home.php");
        }
        else
        {
            echo '<script>alert("Error 1")</script>';
        }
    }
}
else
{
    echo '<script>alert("Error2")</script>';
}


?>
php session password-hash
1个回答
2
投票

我想我看到了问题。

似乎您可能正在从if之前的结果中获取唯一的行

$row = mysqli_fetch_assoc($result);

然后,当您再次在这里获取时,没有任何东西可以获取。

if(($result->num_rows > 0))
{
    while($row = mysqli_fetch_array($result))

(我假设查询将仅返回一行,因为用户名是唯一的。)

© www.soinside.com 2019 - 2024. All rights reserved.