Home > Article > Backend Development > Why does PHP password verification fail with a password hash mismatch?
PHP password_hash(), password_verify()
In your registration script, you correctly hash the password using password_hash() and store it in the database. However, when verifying the password during login using password_verify(), you're encountering a mismatch.
The snippet you provided shows that the password stored in the database is hashed (starting with "$2y$10$"), while the password entered by the user is in plain text (string(1) "1"). The problem lies in the way you retrieve the password from the database.
In the login script, you retrieve the password column directly from the database result without any further processing. However, the stored password is hashed, and it needs to be unhashed before it can be compared to the plain text password entered by the user using password_verify().
Solution:
In the login script, before using password_verify(), you need to retrieve the stored hashed password from the database and then unhash it using the password_hash() function with the PASSWORD_DEFAULT algorithm. Here's the corrected code for the login script:
<code class="php">// ...same code as before... $stored_hash = $row['password']; // Retrieve the stored hashed password if (password_verify($pwd, $stored_hash)) { // ...same code as before... }</code>
This modification ensures that the password stored in the database is properly unhashed before being compared to the plain text password entered by the user, allowing password_verify() to function correctly.
The above is the detailed content of Why does PHP password verification fail with a password hash mismatch?. For more information, please follow other related articles on the PHP Chinese website!