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>';
}
?>
Your issue is that you are adding a newline at the end of the hashed string.
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...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.
password_hash()
documentation