Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Password changing code error

I am using password_hash function, it work's well in registration form and login form but doesn't work during change password form, it gives me error message incorrect old password may be my code has gone wrong or may be because password_hash generates different set of characters each time even with the same input, if it is so what method is used to update password. the same code works using md5.

if(isset($_POST['senddata'])){
    $old_password = $_POST['oldpassword'];
    $new_password = $_POST['newpassword'];
    $repeat_password = $_POST['newpassword2'];    

    $query = $db->prepare("SELECT * FROM users WHERE username=:username");
    $query->execute(array(':username'=>$username));
    $row = $query->fetch(PDO::FETCH_ASSOC);
    $db_password=$row['password'];
    // hash old password before match
    $old_password = password_hash($old_password, PASSWORD_DEFAULT);
    // check if old password equals db_password
    if ($old_password==$db_password) {
        // continue changing users password
        if ($new_password==$repeat_password) {
            // hash the new password
            $new_password=password_hash($new_password, PASSWORD_DEFAULT);
            $repeat_password=password_hash($repeat_password, PASSWORD_DEFAULT);
            // update password
            $password_update_query=$db->prepare("UPDATE userss SET password=:password, password2=:password2 WHERE username=:username");
            $password_update_query->execute(array(':password'=>$new_password,':password2'=>$repeat_password2,':username'=>$username));
            echo "Your Password Updated";
        }
    } else {
        echo "Old password is incorrect";
    }
}

1 Answers

You need to use password_verify($password, $hash); for verifying that passwords are equal

When you hash it again you get a other result because it generates a new salt, which then result in an other hash.

Something like:

$old_password = $_POST['oldpassword'];
$db_password = $row['password']; // which should be already hashed
if (password_verify($old_password, $db_password) {
like image 116
jmattheis Avatar answered Feb 19 '26 22:02

jmattheis