Hash and verify passwords in PHP - the right way


Please contribute by voting. Thanks!
It is easy to do password security wrong in any language. PHP makes it very easy to do this right, but yet (partly due to very old tutorials) many do this the wrong way, and the end result might be totally insecure. This is how it is done the right way:

Hash passwords

Do NOT hash passwords yourself, PHP has a built-in function that does everything for you in a secure manner - password_hash:
$password = "asdf123";
$secret = password_hash($password, PASSWORD_BCRYPT);
//Store $secret in database

The password_hash will use a secure hash algorithm as well as seed it with a cryptographically secure pseudorandom salt. It will then return this information (hash + salt) in a single string suitable for storing with the user's record in the database.

Verify password

Again - do NOT verify the password yourself, PHP has a built-in function that does this for you in a secure manner - password_verify:
if (password_verify($password_entered, $stored_secret))
  //Password OK
  //Password not OK
Simple and secure!

NB. Also do not forget to use the function password_needs_rehash when authenticating users. This enables you to update algorithms as the currently recommended standards changes.

Article created: Aug 1 '15. Edited Sep 22 '15.


Woody Gilk [3]  •  Sep 22 '15  •   •  Reply

You should also mention http://php.net/password_needs_rehash

Beace Meker [1]  •  Nov 20 '17  •   •  Reply

From the php manual regarding "password_needs_rehash"

"password_needs_rehash — Checks if the given hash matches the given options"

Which means it is needed if the option parameter is changed. Option were not given by the user the manual says

"If omitted, a random salt will be created and the default cost will be used.

The question here is If I do not change the default cost, why would I need to use the password_needs_rehash?

Your comment

You need to sign up / log in to comment this article


Created by Robert Bengtsson [128] Aug 1 '15

Share article

Do you know about

Domain-driven Design (DDD)?

Write an article