Authentication

Secure Password Storage and Password Policy in PHP

Store passwords with PHP's password API and protect authentication flows against common mistakes.

Hash passwords

$hash = password_hash($password, PASSWORD_DEFAULT);

Store the result in a column large enough for future algorithms, commonly VARCHAR(255). Never store plaintext passwords or use reversible encryption for password storage.

Verify passwords

if (password_verify($submittedPassword, $storedHash)) {
    // Credentials are valid.
}

Rehash when needed:

if (password_needs_rehash($storedHash, PASSWORD_DEFAULT)) {
    $newHash = password_hash($submittedPassword, PASSWORD_DEFAULT);
    // Save the new hash.
}

Design a sensible policy

Encourage long, unique passwords and allow password managers and paste operations. Avoid arbitrary composition rules that encourage predictable patterns.

Protect the login flow

Use generic failure messages, rate limiting, secure sessions, and multi-factor authentication for high-risk accounts. Reset tokens should be random, short-lived, single-use, and stored as hashes.