security
Password Hashing
Passwords must be stored as slow one-way hashes, never plaintext or reversible encryption. PHP provides the high-level password API so applications can use safe defaults and upgrade hashes over time.
Core Controls
- Create hashes with
password_hash()and verify them withpassword_verify(). - Use
PASSWORD_DEFAULTunless the project deliberately configures another supported algorithm. - Call
password_needs_rehash()after successful login and save an upgraded hash when needed. - Do not log passwords or send them to analytics.
- Use generic authentication failures and rate limiting around login attempts.
Hash And Verify With PHP's Password API
<?php
declare(strict_types=1);
$storedHash = password_hash('correct horse battery staple', PASSWORD_DEFAULT);
var_dump(password_verify('correct horse battery staple', $storedHash));
var_dump(password_verify('wrong password', $storedHash));
// Prints:
// bool(true)
// bool(false)
The stored hash includes the information PHP needs to verify the password. Do not add a home-grown salt format or compare hashes manually.
Rehash During Login
Password algorithms and cost settings change over time. After a successful login, check whether the stored hash should be upgraded:
<?php
declare(strict_types=1);
function shouldUpgradePasswordHash(string $hash): bool
{
return password_needs_rehash($hash, PASSWORD_DEFAULT);
}
If it returns true, hash the submitted password again and save the new hash. This improves existing accounts gradually without forcing a mass password reset.
Protect The Whole Login Flow
Use generic failure messages, rate limits, HTTPS, secure sessions, and careful logging. Password-reset links are credentials too: generate unpredictable tokens, expire them, make them single-use, and store only a digest where practical.
In Application Work
The hash column must be wide enough for future algorithms. Password-reset tokens are separate credentials and need their own secure random generation, expiry, and hashing strategy.
What To Check
Before moving on, make sure you can hash and verify passwords with PHP's password API, explain rehashing, protect login failures, and treat reset tokens as separate credentials.
Practice
Practice: Model A Password Login
Requirements
- Hash a password with PHP's password API.
- Verify a correct and incorrect password.
- Check whether the stored hash needs rehashing.
- Do not expose the password or hash in output.
Show solution
Review Points
- Create hashes with
password_hash()and verify them withpassword_verify(). - Use
PASSWORD_DEFAULTunless the project deliberately configures another supported algorithm. - Call
password_needs_rehash()after successful login and save an upgraded hash when needed. - Do not log passwords or send them to analytics.
- Use generic authentication failures and rate limiting around login attempts.