PHP: How to use password_hash and password_verify

In this article I will describe how to use two PHP functions, password_hash and password_verify, that are important for website login pages that use a user name and password.

1. password_hash()

Here is what the PHP documentation says about password_hash:

password_hash() creates a new password hash using a strong one-way hashing algorithm. password_hash() is compatible with crypt(). Therefore, password hashes created by crypt() can be used with password_hash().

What is a password hash? Here is how Wired describes a hash:

A hash is designed to act as a “one-way function”: A mathematical operation that’s easy to perform, but very difficult to reverse. Like other forms of encryption, it turns readable data into a scrambled cipher. But instead of allowing someone to decrypt that data with a specific key, as typical encryption functions do, hashes aren’t designed to be decrypted. Instead, when you enter your password on a website, it simply performs the same hash again and checks the results against the hash it created of your password when you chose it, verifying the password’s validity without having to store the sensitive password itself.

https://www.wired.com/2016/06/hacker-lexicon-password-hashing/

password_hash() uses two arguments, password and hash algorithm:

password_hash( $password, PASSWORD_DEFAULT )

Example of usage:

echo password_hash("rasmuslerdorf", PASSWORD_BCRYPT);

2. password_verify()

The password_verify() function verifies that a password matches a hash. It is a PHP boolean function that returns true if the password matches the hash, or false if it doesn’t.

Here is what the PHP documentation says about password_verify:

Verifies that the given hash matches the given password.

Note that password_hash() returns the algorithm, cost and salt as part of the returned hash. Therefore, all information that’s needed to verify the hash is included in it. This allows the verify function to verify the hash without needing separate storage for the salt or algorithm information.

This function is safe against timing attacks.

Syntax:

password_verify ( $password , $hash )

Example of usage:

<?php
// See the password_hash() example to see where this came from.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

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

password_hash is used to create the hash, and password_verify uses the hash every time your website needs to verify a user login.

For more information about password_hash, see:
https://secure.php.net/manual/en/function.password-hash.php

For more information about password_verify, see:
https://secure.php.net/manual/en/function.password-verify.php