How to Use the PHP password_verify() Function

09/05/2021
Contents
In this article, you will learn how to use the PHP password_verify() function.
PHP password_verify() Function
The password_verify() function in PHP is used to verify that a given password matches a hashed password.The function returns TRUE if the plain text password matches the hashed password and FALSE otherwise.
Syntax:
password_verify(string $password, string $hash): bool
Parameters:
The function takes two arguments:
- $password: The plain text password (the password to be verified)
- $hash: The hashed password (the reference password)
Example:
Here’s an example usage:
<?php
$plain_password = 'secret_password';
$hashed_password = '$2y$10$q3a0zMCTcLFHv4zf.GtoIuRbR/ZGjA6gSk/6/sU6HYsUzE/NQXgL6';
if (password_verify($plain_password, $hashed_password)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
?>
Note: The password_hash() function is usually used to generate the hashed password before storing it in a database.
Here are a few additional details:
- The password_verify() function uses the bcrypt algorithm to hash passwords, which is considered to be a strong and secure algorithm.
- It is important to use the password_hash() function to hash passwords before storing them in a database, rather than hashing them yourself. the password_hash() function automatically generates a unique salt for each password hash, making it more secure.
- The password_verify() function takes care of checking the hashed password against the given password, including checking the salt and other information included in the hashed password.
- When storing passwords, it is important to use a secure method to store them, such as using a secure database. Storing passwords in plain text is never recommended.
- The password_verify() function is available in PHP 5.5.0 and later, so if you’re using an earlier version of PHP, you will need to upgrade or use an alternative method for password verification.
- The password_verify() function should be used in conjunction with the password_hash() function for maximum security.