简体   繁体   中英

php old password check from database

I am creating PHP hash password update script this script working and updating new hash password but not checking old hash password I want to create old hash password check and update new password

Here is my code

<?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";
 }
}
?>

This is my HTML form

<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>

You're comparing the $old_password from the user to the $new_password from the user. This is wrong. You want to compare the $old_password from the user to what's in the database. Then, if that succeeds, save the hash of $new_password to the database. Assuming you pull the result of your SELECT into an array named $row , something like:

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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