php password_verify doesn't work

2.1k Views Asked by At

This should be very straight forward: I'm generating a hashed password and then want to compare it to the "unhashed" string. It always returns invalid password. What am I missing?

<?php

// MY CURRENT PHP VERSION IS 7.0.9

$password = "abc";

$options = [
    'cost' => 11,
    'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
];
$password_hashed = password_hash($password, PASSWORD_BCRYPT, $options)."\n";

if (password_verify($password, $password_hashed)) {
    echo '<strong>correct password.</strong><br>';
} else {
    echo '<strong>invalid password!</strong><br>';
}


?>
1

There are 1 best solutions below

0
On BEST ANSWER

Your issue is that you are adding a newline at the end of the hashed string.

$password_hashed = password_hash($password, PASSWORD_BCRYPT, $options)."\n";
//                                                                       ^
//                                          Here you add a newline ------'

That means that you hash the password, and add a newline at the end of the hashed string. When you now compare against the unhashed string through password_verify(), it won't match - simply because of that newline. To solve the issue, you need to remove ."\n" from where you hash the password, making it...

$password_hashed = password_hash($password, PASSWORD_BCRYPT, $options);

The newline probably comes from the PHP manual, where they show examples of hashing the passwords. Unfortunately, it's quite misleading - and should in my opinion be removed from the examples.

As a final note, from the manual.

Warning
The salt option has been deprecated as of PHP 7.0.0. It is now preferred to simply use the salt that is generated by default.