PHP password_verify

Summary: in this tutorial, you’ll learn to use the PHP password_verify() function to check if a password matches a hashed password.

Introduction to the PHP password_verify() function

When dealing with passwords, you should never store them in the database as plain text. And you should always hash the passwords using a secure one-way hash algorithm.

PHP provided the built-in password_hash() function that creates a hash from a plain text password. Note that the password_hash() function is a one-way hash function. It means that you cannot find its original value.

To verify if a plain text password matches a hashed password, you must hash the plain text password and compare the hashes.

However, you don’t have to do it manually since PHP provides you with the built-in password_verify() function that allows you to compare a password with a hash:

password_verify(string $password, string $hash): bool
Code language: PHP (php)

The password_verify() has two parameters:

  • $password is a plain text password to match.
  • $hash is a hash created by the password_hash() function.

The password_verify() function returns true if the password matches the hash or false otherwise.

PHP password_verify() function example

The following example uses the password_verify() function to check if the password Password1 matches a hash:

<?php $hash = '$2y$10$hnQY9vdyZUcwzg2CO7ykf.a4iI5ij4Pi5ZwySwplFJM7AKUNUVssO'; $valid = password_verify('Password1', $hash); echo $valid ? 'Valid' : 'Not valid';
Code language: PHP (php)

Output:

Valid
Code language: PHP (php)

In practice, you’ll use the password_verify() function as following to verify a login:

  • Find a user from the database by a username (or email)
  • Use the password_verify() function to match the user’s provided password with a hashed password.
  • If the password matches the hash, you log the user in. Otherwise, you’ll issue an error message.

The code will look like the following:

<?php // ... $user = find_user_by_username($username); if ($user && password_verify($password, $user['password'])) { // log the user in session_regenerate_id(); $_SESSION['user_id'] = $user['id']; } else { echo 'Invalid username or password'; }
Code language: PHP (php)

In the following tutorial, you’ll learn to use the password_verify() function in the login form.

Summary

  • Use the PHP password_verify() function to check if a password matches a hashed password created by the password_hash() function.
Did you find this tutorial useful?