PHP Securely Save Passwords in Your Database

Posted on March 9, 2019 at 9:00 pm

To securely save passwords in your database you should use password_hash()!

When the user registers, you hash the password and then save it to the database:

// Create the hashed password from the user submitted password
// Notice that we hash() the password using sha256 before creating the hashed password
 
$hashed_password = password_hash(hash("sha256", trim($_POST["password"])), PASSWORD_BCRYPT);
 
// Now save the hashed password in the database

It is the most secure way to store a password in your database in hash format! The function password_hash() automatically generates the salt (dont’ create your own!) and is much better than storing the password hashed using just md5() or sha1().

Hash the password before password_hash()

You may have noticed that we hash() the password using sha256 before creating the hashed password because bcrypt(), the algo used by password_hash(), may silently truncate the string if it is longer than 72 characters or if it contains NUL chars.

Specify what algorithm to use!

Another good information is that we use PASSWORD_BCRYPT as algo because the constant PASSWORD_DEFAULT is designed to change over time as new and stronger algorithms are added to PHP. Hence why we expressely specify which algo to use, else when a new PHP version will be released (i.e PHP 7.8.5), PASSWORD_DEFAULT may not refer anymore to bcrypt and this may create problems in your PHP application.

How to verify the password

Then to verify the password when the user login, you can use password_verify():

// Retrieve the hashed password from your database
 
$hashed_password = "select hashed_password from users where user_id = 123";
 
// Now verify the user submitted password with the hashed password
 
if(password_verify(hash("sha256", trim($_POST["password"])), $hashed_password))
{
    echo "Welcome";
}
else
{
    echo "Wrong Password!";
}

Update March 2019

May be better to use the algo Argon2 (available from PHP 7.2.0, only if PHP has been compiled with Argon2 support) instead of the default bcrypt.

Updated on March 15, 2019 at 4:10 pm

Receive updates via email

Other Posts

Updated Posts