Skip to content
GreenSnippets

Hash and verify passwords in PHP

Store passwords with password_hash and check them with password_verify, including rehash on login.

PHP
<?php
function hashPassword(string $password): string
{
    return password_hash($password, PASSWORD_DEFAULT);
}

/** Returns [bool $valid, ?string $newHash] - persist $newHash if it is not null. */
function verifyPassword(string $password, string $storedHash): array
{
    if (!password_verify($password, $storedHash)) {
        return [false, null];
    }
    $newHash = password_needs_rehash($storedHash, PASSWORD_DEFAULT)
        ? password_hash($password, PASSWORD_DEFAULT)
        : null;
    return [true, $newHash];
}

How it works

Never store plain or fast-hashed (MD5, SHA-1, SHA-256) passwords. password_hash with PASSWORD_DEFAULT uses a strong, salted, adaptive algorithm (currently bcrypt) and embeds the salt and cost in the result, so you store only that one string.

On each successful login call password_needs_rehash; if PHP's default has gotten stronger, store the new hash. Note that bcrypt only uses the first 72 bytes of input.