0
0
PhpHow-ToBeginner · 3 min read

How to Use password_verify in PHP for Secure Password Checking

Use password_verify in PHP to check if a plain password matches a hashed password securely. It takes two arguments: the plain password and the hashed password, returning true if they match and false otherwise.
📐

Syntax

The password_verify function requires two parameters:

  • password: The plain text password to check.
  • hash: The hashed password to compare against.

It returns true if the password matches the hash, otherwise false.

php
bool password_verify(string $password, string $hash)
💻

Example

This example shows how to hash a password and then verify it using password_verify. It prints whether the password is correct or not.

php
<?php
// Hash a password
$hashedPassword = password_hash('mypassword123', PASSWORD_DEFAULT);

// User input password to check
$inputPassword = 'mypassword123';

// Verify the password
if (password_verify($inputPassword, $hashedPassword)) {
    echo "Password is correct.";
} else {
    echo "Password is incorrect.";
}
?>
Output
Password is correct.
⚠️

Common Pitfalls

Common mistakes when using password_verify include:

  • Comparing the plain password directly to the hash using == or === instead of using password_verify.
  • Not hashing the password first with password_hash before storing it.
  • Using outdated hashing methods instead of password_hash and password_verify.

Always use password_verify to check passwords securely.

php
<?php
// Wrong way: direct comparison (DO NOT DO THIS)
$hash = password_hash('secret', PASSWORD_DEFAULT);
$input = 'secret';
if ($input === $hash) {
    echo "Match";
} else {
    echo "No match";
}

// Right way:
if (password_verify($input, $hash)) {
    echo "Match";
} else {
    echo "No match";
}
?>
Output
No matchMatch
📊

Quick Reference

FunctionPurposeNotes
password_hashCreates a secure hash from a plain passwordUse PASSWORD_DEFAULT for best algorithm
password_verifyChecks if a plain password matches a hashReturns true or false
password_needs_rehashChecks if hash needs updatingUse to upgrade hash algorithms

Key Takeaways

Use password_verify to safely check plain passwords against hashed passwords.
Never compare plain passwords directly to hashes with == or ===.
Always hash passwords with password_hash before storing them.
password_verify returns true if the password matches the hash, false otherwise.
Use password_needs_rehash to keep hashes up to date with current algorithms.