我正在创建PHP哈希密码更新脚本,此脚本可以正常工作并更新新的哈希密码,但不检查旧哈希密码。我想创建旧哈希密码检查并更新新密码
这是我的代码
<?php
include("database/config.php");
if($_SERVER['REQUEST_METHOD'] == "POST"){
$old_password = $_POST['old_password'];
$new_password = $_POST['new_password'];
$con_password = $_POST['con_password'];
$stmt = $con->prepare('SELECT * FROM users WHERE user_id= ?');
$stmt->bind_param('s', $_SESSION['user_id']);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows >0){
$stmt->fetch();
$hash = password_hash($_POST['old_password'], PASSWORD_DEFAULT);
if(password_verify($_POST['new_password'], $hash)){
if ($new_password == $con_password) {
if ($stmt = $con->prepare("UPDATE users SET password = ? WHERE user_id = ?")) {
$stmt->bind_param('ss', $hash, $_SESSION['user_id']);
$stmt->execute();
echo "Updated Sucessfully";
}
}else {
echo "Your new Password is not match ";
}
}
}else {
echo "Your old password is incorrect";
}
}
?>
这是我的HTML表单
<form name="form1" method="post" action="">
<input name="old_password" type="password" id="old_password" value="" placeholder="Current Password" required>
<input name="new_password" type="password" id="new_password" value="" placeholder="New Password" required>
<input name="con_password" type="password" id="con_password" value="" placeholder="confirm new password" required>
<input type="submit" name="changePass" value="change password" class="submit2" />
</form>
答案 0 :(得分:3)
您正在比较用户的$old_password
和用户的$new_password
。错了您想将来自用户的$old_password
与数据库中的内容进行比较。然后,如果成功,则将$new_password
的哈希保存到数据库中。假设您将SELECT的结果拉入名为$row
的数组中,例如:
if ($_POST['new_password'] !== $_POST['con_password']) {
// new password and confirm password don't match, abort
} else {
if (password_verify($_POST['old_password'], $row['password']) {
// user gave good old password, so save the new one
$hash = password_hash($_POST['new_password'], PASSWORD_DEFAULT);
// UPDATE users SET password = :hash WHERE user_id = :user_id
// bind $hash to :hash
// bind $row['user_id'] to :user_id
} else {
// user gave bad old password, abort
}
}