简体   繁体   English

如何针对数据库检查哈希密码

[英]How to check a hashed password against database

I am looking to check the username and password that are entered are equal to the username and password stored in mysql database. 我正在检查输入的用户名和密码是否等于存储在mysql数据库中的用户名和密码。

I have used password_hash() to hash the password and stored them into table. 我已经使用password_hash()哈希密码并将其存储到表中。 But I don't know, how to check if they are the same or not. 但我不知道如何检查它们是否相同。

HTML 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

<?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);
?>

Also, do I have to escape the password input if it is hashed? 另外,如果输入的密码经过哈希处理,是否必须转义?

You need to get the input password hashed again and before binding it with your prepare statement. 您需要再次将input密码散列,然后再将其与prepare语句绑定。 You need to make sure, you are using same encryption method, which was used for storing. 您需要确保使用的是用于存储的相同加密方法。

$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);

Edited: 编辑:

As suggested by @Devon in comment, you could also use password_verify 正如@Devon在评论中建议的那样,您也可以使用password_verify

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM