PHP Tutorials
Oct 12, 2022

PHP Password_Verify() Function - Verify That A Hash Matches A Given Password

Let's take a look at how we can use the password_verify() function to match a hash and password str

Matt Payne
Matt Payne

We're going to look at how we can use the password_verify() function to verify that a given password matches a previously hashed password. We'll walk through some examples to see how this function can be used in a production setting.

PHP Password_Verify() Function Introduction & Syntax

The PHP password_verify() function is a built-in function that was introduced with PHP 5.5.0. This function is used to verify a given password against a password hash created by the password_hash() function. A typical workflow with the password_verify function might look something like this: User submits their login credentials to the login page. Their inputted password gets hashed using the password_hash() function. This hash gets stored in our user database. The stored password hash gets compared to the newly inputted password hash created with password_hash(). This comparison is done using the password_verify function.

Parameters For The Password_Verify() Function

The first parameter is the given password that needs to be verified against the second parameter, the hash. Both of these parameters are mandatory.

Password String

The first parameter is the string version of the password we want to compare. This parameter is mandatory.

Hash

The $hash parameter is our password hash created using the password_hash() function which uses the bcrypt hashing algorithm. This parameter is mandatory.

Return Values For The Password_Verify() Function

The function returns either a boolean true or false based on if the $hash could be verified with the given $password. If the $hash has been salted, then the $password must include the same salt at the beginning of the password and may also contain data such as the algorithm, cost, and salt.

Quick Notes About The PHP Password Verify Function

This function checks for a hash match between the two string variables. This function will return false if $hash is of an invalid format. This function uses the timing attack safe string comparison function provided by hash_equals(). 

PHP Password_Verify() Example

Let’s look at an example of how we can use the password_verify() function to compare a string variable to a hash.

Simple Password_Verify() Comparison Example

This 3 step example below creates a new user’s $password and stores a password string inside of it. Then we create another variable $hash and store the password_hash() function output. This function returns the cryptological hash of our $password variable which we can store and use to verify against user input later.


//create new password 
$password = 'mypassword'; 
//create hash of password 
$hash = password_hash($password, PASSWORD_DEFAULT); 
//store returned hash in database for later comparison
// Returns algorithm information, salt, and costecho $hash; 

The result of this code will return a hash of our $password variable. This is useful for storing in a database for comparison later against a user input value.

Verify Submitted Password Against Hash

This example below builds on the previous one and uses the $hash to verify the password against user input. In this case, we’re using the same password but you could use different ones.


//original password 
$password = 'mypassword'; 
//stored hash $hash = '$2y$10$RMiB.IAcbvx1tRksRJgHverMWf7meHDqAw3gUc/oG/xHU1f6UgJ6a'; 
if (password_verify($password, $hash)) { 
	echo 'Password is valid!'; } 
else { 
	echo 'Invalid password.'; }

The result of this code snippet is ‘Valid password.’ If we were to change our $password variable to ‘notmypassword’ we would see ‘Invalid password.’ displayed.

Upgrade Hash If Hash Needs Rehashing

This final simple code example builds on previous ones and demonstrates how to verify a password and if need be rehash it to upgrade the encryption. 


// Store the password hash into database
$password = 'mypassword';‍
// Create the hash$hash = password_hash($password, PASSWORD_DEFAULT);‍
// Verify the password against the hash‍
if (password_verify($password, $hash)) {    
	echo 'Password is valid!';} 
else {    
  echo 'Invalid password.';}‍
  // Verify if the hash needs to be rehashed‍
  if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {    
  // Check if the hash is out of date and needs to be upgraded    
  $newHash = password_hash($password, PASSWORD_DEFAULT);‍    // Replace the old hash with the new one    
}

The result of this code is ‘Password is valid!’. This lets us know that our hash is working correctly. If we need to update the hash, we can do so by checking if password_needs_rehash returns true and perform an update

Deeper Examples of Password_Verify() Function

A few more quick use cases that provide real world application. 

Verify password against database records

If you are verifying a password against a database, use password_verify(). If you are just verifying two passwords entered by the user (e.g. during registration), use hash_equals().


// Get the password from post $password = $_POST['password'];
// Load password hash from database 
$hash = $user['password'];
if (password_verify($password, $hash)) { 
// Password is correct! // Log the user in here. 
} 
else { // Invalid password 
}

This is also useful if you need to verify multiple passwords. Just hash each password with password_hash() and compare them with hash_equals().

PHP password_verify() forgot password example

When a user forgets their password, they will enter their email address on the forgot password page. Then, we will look up their account in the database and send them an email with a link to reset their password.


$email = $_POST['email'];$check = mysqli_query($conn, "SELECT * FROM users WHERE email = '$email'");
$checkrows = mysqli_num_rows($check); 
if($checkrows > 0){ 
// we found an account! 
	$str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
	$str = str_shuffle($str); 
	$str = substr($str, 0, 15); 
	$url = "http://www.example.com/reset.php?key=$str&reset=$email"; 
	$message = "To reset your password, please visit the following link:\n\n"; 
	$message .= $url; 
	if(mail($email, 'Reset Password', $message, 'From:'.'noreply@example.com')){ 
		echo "A password reset link has been sent to $email"; 
    }
} 
else { // no account found! echo "No account found for $email"; }

In the code above, we are using PHP’s mail() function to send an email to the user with a link to reset their password. The link will include a random string of characters (which we generated with PHP’s str_shuffle() and substr() functions) and the user’s email address. When the user clicks on the link, they will be taken to a reset.php page, where we will verify the key and email address before allowing the user to change their password.

Summary

The Password_Verify() function is a great way to verify that a given password matches a stored password hash. The function takes the given password and compares it to the password hash created by the password_hash() function. If the two match, then the function returns true, otherwise it returns false.

php logo

Instant Access To PHP Case Studies

Read real use cases and whitepapers using PHP