PHP

Lesson 05

Password hashing and verification

Store password hashes with PHP password APIs and verify them without inventing custom hashing rules.

Good Code

src/Auth/Passwords.php
<?php declare(strict_types=1);

function hashPassword(string $plainPassword): string
{
    return password_hash($plainPassword, PASSWORD_DEFAULT);
}

function verifyPassword(string $plainPassword, string $storedHash): bool
{
    return password_verify($plainPassword, $storedHash);
}

function shouldRehash(string $storedHash): bool
{
    return password_needs_rehash($storedHash, PASSWORD_DEFAULT);
}

Bad Code

login.php
<?php

$hash = md5($_POST['password']);

if ($hash === $user['password_hash']) {
    $_SESSION['user_id'] = $user['id'];
}

Review Notes

What to review

Good Code

The good version relies on PHP password APIs, which store the algorithm and cost information in the hash and can signal when rehashing is needed.

Bad Code

The bad version uses a fast hash that is not designed for passwords, and it couples login success directly to session mutation.

Takeaways

  • Passwords should go through password_hash and password_verify, never fast general-purpose hashes.