Authentication & Password Hashing
Prerequisites: Working with databases: PDO
Never store a password in plain text — PHP's built-in functions handle secure hashing without needing a third-party library.
$hash = password_hash('correct horse battery staple', PASSWORD_DEFAULT);
// store $hash in the database, never the raw password
if (password_verify('correct horse battery staple', $hash)) {
echo 'Password matches';
}
Combined with sessions (Level 1), this is the core of a login
system: verify the password against the stored hash, then set
$_SESSION['user_id'] on success.
Common mistakes
- Using
md5()orsha1()for passwords — both are fast hashes designed for checksums, not passwords, and are crackable at scale.password_hashuses a slow, purpose-built algorithm (bcrypt by default) specifically to resist this.