Using password_hash and password_verify [duplicate]
In my Login PHP file I have these
$passwordInput = password_hash($passInput, PASSWORD_BCRYPT);
$passwordVerify = password_verify($userInput, $passwordInput);
And in my Register PHP file I have this.
$passwordSign = password_hash($passSign, PASSWORD_BCRYPT);
Now, essentially I make it so it hashes the password and inserts itself into the database on signup. WHICH IT DOES.
However, it cannot verify it. Both results give 2 different hashes and I don't know what I'm possibly doing wrong. I also tried just making it hash the input again and checking the password_hash in the database but that didn't work..
What is the proper way of using these?
( Also, $passSign and $userInput are the input fields and it does get the username/password )
Solution 1:
On signup you get the password from the user input and generate its has using password_hash()
:
$hash = password_hash($_POST['password'], PASSWORD_BCRYPT);
You can provide it a custom salt to use, in a third parameter, but the documentation recommends to not do this:
Caution It is strongly recommended that you do not generate your own salt for this function. It will create a secure salt automatically for you if you do not specify one.
You save this hash in the database. Make sure you put it in a CHAR
/VARCHAR
field of 60 characters or longer.
When the user wants to log in you check the password they input against the hash previously saved using password_verify()
:
$auth = password_verify($_POST['password'], $hash);
Of course, you get the correct value of $hash
from the database, searching by the provided username.
If $auth
is TRUE
then the provided password matches its hash computed on the registration and the user is authenticated.