Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Web and Security

PHP password_verify() function

Reference for PHP password_verify(): check a password against a stored hash, rehash old hashes at login with password_needs_rehash(), and avoid timing leaks.

password_verify() checks whether a plain-text password matches a hash created by password_hash() (or by crypt()). It reads the algorithm, cost and salt from the hash itself, recomputes, and compares in constant time, so you do not need to store anything else.

It returns true or false and never throws for a wrong password. Together with password_needs_rehash() it is the whole login-side API.

PHP
if (password_verify($input, $storedHash)) {
    // correct
}

Try it

PHP Checking a login

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Upgrading hashes at login

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
password_verify(string $password, string $hash): bool
password_needs_rehash(string $hash, string|int|null $algo, array $options = []): bool
Name Description
$password The plain-text password the user typed.
$hash The stored hash string.
$algo, $options For password_needs_rehash(): the algorithm and options you want today.

Return value: true if the password matches; false otherwise, including when $hash is malformed. password_needs_rehash() returns true when the hash was made with a different algorithm or settings.

Usage notes

  • Always compare with password_verify(), never === or ==. It is timing-safe and understands every supported format.
  • Do not reveal which part failed. Return one generic "invalid email or password" message, and run password_verify() even for unknown users (against a dummy hash) so response time does not expose which emails exist.
  • Rehash after a successful check. Only then do you have the plain password in hand. Update the stored hash when password_needs_rehash() says so.
  • Limit attempts. The slow hash protects stolen databases, not live login forms: add rate limiting or lockouts.
  • Trim nothing. Spaces are part of the password. Do not alter the input before verifying.
  • Legacy hashes. password_verify() also accepts old crypt() hashes, but not raw md5() or sha1() strings. Migrate those by verifying with the old function once, then storing a new hash.
  • Bcrypt limit. Only the first 72 bytes of a password count, so two longer passwords sharing those bytes verify equally.