donglv1831 2017-09-30 18:39
浏览 166
已采纳

如何检查数据库的哈希密码

I am looking to check the username and password that are entered are equal to the username and password stored in mysql database.

I have used password_hash() to hash the password and stored them into table. But I don't know, how to check if they are the same or not.

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

Also, do I have to escape the password input if it is hashed?

  • 写回答

1条回答 默认 最新

  • douxianxing5712 2017-09-30 18:43
    关注

    You need to get the input password hashed again and before binding it with your prepare statement. 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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真