How to hash and verify the password?

When you develop any application that accepts passwords from users, you should store passwords hashed. It's the basic rule of security.

Probably you know basic hash functions such as sha1() or md5(). These algorithms are designed to be very fast and efficient. But with modern techniques and computers it's not very hard to use “brute force” to determine the original input. Of course you can use your own “salt solution” for passwords but from PHP 5.5 you can use password_hash() function for password hashing and password_verify() function for the hash verification.

password_hash() will create a random salt if one isn't provided, and this is generally the easiest and most secure approach.

Next advance of the password_hash() function is that you can specify algorithm – by predefined constants PASSWORD_DEFAULT or PASSWORD_BCRYPT, salt (if omitted, a random salt will be generated) and cost - which denotes the algorithmic cost that should be used.

The examples with format desription of output of the password_hash() function for the 'MySecretPassword' string:


Algorithm options (e.g. cost)
Hashed password

How to hash and how to verify passwords?

$password = 'MySecretPassword';
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
//$hashedPassword contains something like
// $2y$10$mXIc4sRxAA7zEuBdaiPwXOBz.PktMmORr1rR.G3FdcuQOTke3fIaq
//you can store it into database

$hash = '$2y$10$mXIc4sRxAA7zEuBdaiPwXOBz.PktMmORr1rR.G3FdcuQOTke3fIaq';
$result = password_verify($password,$hash);
//$result contains TRUE if the password and hash match, or FALSE otherwise.