如何根据数据库检查散列密码

How to check a hashed password against database

我正在检查输入的用户名和密码是否与 mysql 数据库中存储的用户名和密码相同。

我已经使用 password_hash() 对密码进行哈希处理并将它们存储到 table 中。但是我不知道,如何检查它们是否相同。

HTML

<!DOCTYPE HTML>  
<html>
<head>
<style>
    .error {color: #FF0000;}
</style>
</head>
<body>

<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
Username: <input type="text" name="username">
<span class="error">* <?php echo $usernameErr;?></span>
<br><br>
Password: <input type="password" name="password">
<span class="error">* <?php echo $passwordErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">

</form>
</body>
</html>

PHP

<?php
error_reporting(E_ALL | E_STRICT);

$servername = "localhost";
$serverUsername = "root";
$serverPassword = "";

// Create connection
$conn = mysqli_connect($servername, $serverUsername, $serverPassword);
mysqli_select_db($conn, 'users');

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";

if (isset($_POST["submit"])) {
    $query = mysqli_prepare($conn, "SELECT * FROM user_logons WHERE Username = ? AND Password = ?");
    mysqli_stmt_bind_param ($query , 'ss' , $username , $password);
    mysqli_stmt_execute($query);
    $username = mysqli_real_escape_string($conn, $_POST["username"]);
    $password = password_hash($_POST["password"], PASSWORD_BCRYPT);
    mysqli_stmt_close($query);

}

$usernameErr = $passwordErr = "";

mysqli_close($conn);
?>

此外,如果输入的密码经过哈希处理,我是否必须对输入的密码进行转义?

您需要再次对 input 密码进行哈希处理,然后 将其与您的 prepare 语句绑定之前。您需要确保,您使用的是与存储相同的加密方法。

$username = mysqli_real_escape_string($conn, $_POST["username"]);
$password = password_hash($_POST["password"], PASSWORD_BCRYPT); 

mysqli_stmt_bind_param ($query , 'ss' , $username , $password);
mysqli_stmt_execute($query);

已编辑:

正如@Devon 在评论中所建议的,您还可以使用 password_verify