Lesson 4 of 7
Password Hashing - bcrypt & Argon2
Passwords must never be stored in plain text or with reversible encryption. PHP's password_hash() uses bcrypt or Argon2 - adaptive cost algorithms that are intentionally slow to defeat brute-force attacks. When attackers get your database, slow hashing buys users time to change passwords.
Password Hashing - Full Auth Flow
<?php
declare(strict_types=1);
// ── password_hash - the only correct way to store passwords ───
$password = "user_password_here";
// bcrypt (default, industry standard)
$hash = password_hash($password, PASSWORD_BCRYPT, ["cost" => 12]);
// "$2y$12$..." - 60-character bcrypt hash
// Argon2id (PHP 7.3+, more memory-hard - harder to crack with GPUs)
$hash = password_hash($password, PASSWORD_ARGON2ID, [
"memory_cost" => 65536, // 64 MB
"time_cost" => 4, // iterations
"threads" => 3,
]);
// Argon2id is recommended for new systems where PHP 7.3+ is guaranteed
// Always use PASSWORD_DEFAULT for forward-compatibility
// $hash = password_hash($password, PASSWORD_DEFAULT);
// PHP updates this as better algorithms become available
// ── password_verify - always used for checking ────────────────
$inputPassword = $_POST["password"] ?? "";
if (password_verify($inputPassword, $storedHash)) {
// Password is correct
} else {
// Wrong password - same code path for "wrong password" and "user not found"
// (to prevent user enumeration timing attacks)
}
// ── Rehashing - upgrade old hashes when users log in ─────────
if (password_verify($inputPassword, $user["password"])) {
if (password_needs_rehash($user["password"], PASSWORD_BCRYPT, ["cost" => 12])) {
$newHash = password_hash($inputPassword, PASSWORD_BCRYPT, ["cost" => 12]);
// UPDATE users SET password = :hash WHERE id = :id
}
// Log user in...
}
// ── Registration flow ─────────────────────────────────────────
class UserRepository {
public function register(string $email, string $password): array {
// Validate
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException("Invalid email.");
}
if (strlen($password) < 8) {
throw new InvalidArgumentException("Password must be at least 8 characters.");
}
// Check not already registered
$existing = $this->findByEmail($email);
if ($existing !== null) {
throw new RuntimeException("Email already registered.");
// Or return same message as "success" to prevent user enumeration
}
$hash = password_hash($password, PASSWORD_BCRYPT, ["cost" => 12]);
$stmt = $this->pdo->prepare(
"INSERT INTO users (email, password, created_at) VALUES (:email, :pass, UTC_TIMESTAMP())"
);
$stmt->execute([":email" => strtolower(trim($email)), ":pass" => $hash]);
return [
"id" => (int) $this->pdo->lastInsertId(),
"email" => $email,
];
}
}
// ── Password reset - secure token ─────────────────────────────
function generatePasswordResetToken(int $userId): string {
$token = bin2hex(random_bytes(32));
$expires = new DateTimeImmutable("+1 hour");
$hash = hash("sha256", $token); // store hash, send raw token by email
// Store: $hash, $userId, $expires in password_resets table
return $token; // send in email link
}
function verifyResetToken(string $token, string $storedHash, DateTimeImmutable $expiresAt): bool {
if (new DateTimeImmutable() > $expiresAt) return false;
return hash_equals($storedHash, hash("sha256", $token));
}Quick Quiz
Tip
Tip
Practice Password Hashing bcrypt Argon2 in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Password Hashing - bcrypt & Argon2
Practice Task
Note
Practice Task - (1) Write a working example of Password Hashing bcrypt Argon2 from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Password Hashing bcrypt Argon2 is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.
Finished this lesson?