Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php password_hash and password_verify issues no match

I am trying out a new function from PHP 5.5 called password_hash().

No matter what i do the $hash and the $password wont match.

$password = "test";

$hash = "$2y$10$fXJEsC0zWAR2tDrmlJgSaecbKyiEOK9GDCRKDReYM8gH2bG2mbO4e";



if (password_verify($password, $hash)) {
    echo "Success";
}
else {
    echo "Error";
}
like image 889
Daniel Avatar asked Nov 08 '13 09:11

Daniel


Video Answer


3 Answers

The problem with your code is that you are using the double quotation marks " instead of the single quotation marks ' when dealing with your hash.

When assigning:

$hash = "$2y$10$fXJEsC0zWAR2tDrmlJgSaecbKyiEOK9GDCRKDReYM8gH2bG2mbO4e";

It's making php think you have a variable called $2y and another one called $10 and finally a third one called $fXJEsC0zWAR2tDrmlJgSaecbKyiEOK9GDCRKDReYM8gH2bG2mbO4e. Which obviously isn't the case.

I noticed when turning on error reporting that the error:

Notice: Undefined variable: fXJEsC0zWAR2tDrmlJgSaecbKyiEOK9GDCRKDReYM8gH2bG2mbO4e

Was being thrown by PHP.

Replace all your double quote marks with single quote marks to fix.

E.g

$hash = '$2y$10$fXJEsC0zWAR2tDrmlJgSaecbKyiEOK9GDCRKDReYM8gH2bG2mbO4e';

Treats the whole hash as a literal string instead of a string with embedded variables.

like image 165
initramfs Avatar answered Oct 19 '22 14:10

initramfs


I had a similar problem with password_verify().

The mistake in my case, it was that I have declared my password field in the database as varchar(30), but the hash is equal or longer to 60 characters..

like image 20
Antonis Tzilivakis Avatar answered Oct 19 '22 12:10

Antonis Tzilivakis


Works fine for me.

<?php

$hash=password_hash("rasmuslerdorf", PASSWORD_DEFAULT);
if (password_verify('rasmuslerdorf', $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}
?>

OUTPUT:

Password is valid!

like image 42
Shankar Narayana Damodaran Avatar answered Oct 19 '22 14:10

Shankar Narayana Damodaran