Password Hashing & Sessions — PHP

Store the result of password_hash($password, PASSWORD_DEFAULT), not the password. The result is a hash: a one-way result that can be matched but never turned…

Imagine that one day your stall's database leaks. If the password column holds each password as it is, for example "secret", every customer's password can be read right away. And many people use the same password for their email and their bank. If the column holds hashes, all that leaks is strings that can't be turned back into passwords.

Logging in takes two things. First, checking a password without ever storing the real one. Second, remembering who logged in across the requests that follow. Picture a regular customer of Mrs. Tini's Stall who orders through the website. In the customer book, Mrs. Tini doesn't write the password down, only its "fingerprint": a one-way result that can be matched but never turned back into the password. That fingerprint is a hash, and the customer book is the users table in the database. Once the password matches, the customer gets a numbered table card. The card says nothing about them, but at the till there's a note "table 7: Budi". The card and the note together are a session. The browser keeps the number in a cookie (a small piece of data the browser sends again with every request), and the server keeps the note.

Store the hash, not the password

password_hash turns a password into a hash:

<?php
$hash = password_hash("secret", PASSWORD_DEFAULT);
echo $hash;
// $2y$12$JoM1n2WtHuhV6vVF6SV.geOsGjF.i7ylfgyxdxlNILOznmTnvQEGG

That 60-character string is what goes into the password column of the users table. Its parts:

Part Example Meaning
$2y$ $2y$ the algorithm is bcrypt
cost 12$ the work factor: each step up doubles the hashing time
salt JoM1n2WtHuhV6vVF6SV.ge 22 random characters, different on every call
hash OsGjF.i7ylfgyxdxlNILOznmTnvQEGG the result of the password plus the salt

Why must it be a deliberately slow hash like bcrypt or Argon2id, not a fast hash like md5 or SHA-256? In short, a slow hash means an attacker needs a very long time to guess passwords one by one from leaked hashes. The details are in the lesson Password Hashing & Storage in the Security track.

Logging in: password_verify

At login, find the hash for the email the user typed, then match it against the password they typed:

$stmt = $pdo->prepare("SELECT id, password FROM users WHERE email = ?");
$stmt->execute([$_POST["email"] ?? ""]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user || !password_verify($_POST["password"] ?? "", $user["password"])) {
    exit("Wrong email or password.");
}

💡 password_needs_rehash: upgrading old hashes

Budi's hash was made back when the server ran PHP 8.3, so it starts with $2y$10$. After upgrading to PHP 8.4:

var_dump(password_needs_rehash('$2y$10$ZfkPJqxrjAaC9NK0qFXPp.oTl3ff9a9f/W8EdWDiDKp7Nvpj3dcya', PASSWORD_DEFAULT));
// bool(true)

The hash in that code is in single quotes, so PHP doesn't read the parts that start with $ as variables.

password_needs_rehash answers true when the hash's algorithm or cost differs from what's asked for now (cost 10 versus 12, or Argon2id versus bcrypt). You only have the real password at login, when the user types it. So renew the hash there, after password_verify succeeds:

if (password_needs_rehash($user["password"], PASSWORD_DEFAULT)) {
    $newHash = password_hash($_POST["password"], PASSWORD_DEFAULT);
    $pdo->prepare("UPDATE users SET password = ? WHERE id = ?")->execute([$newHash, $user["id"]]);
}

Sessions: session_start and $_SESSION

HTTP (the rules a browser and a server use to exchange requests and responses) remembers nothing between two requests. A session does the remembering:

<?php
session_start();
$_SESSION["user_id"] = 1;

PHP sends this header to the browser (a header is information at the start of the response, before the page content):

Set-Cookie: PHPSESSID=058a6624a1fd3d5a2204f8257a9f7609; path=/

After logging in: session_regenerate_id(true)

When the password matches, make a new session ID before saving the user:

if (password_verify($_POST["password"], $user["password"])) {
    session_regenerate_id(true);
    $_SESSION["user_id"] = $user["id"];
}

💡 A safe session cookie, and logging out

A session cookie should get some extra settings:

session_set_cookie_params([
    "lifetime" => 0,
    "path" => "/",
    "secure" => true,
    "httponly" => true,
    "samesite" => "Lax",
]);
session_start();

The header sent becomes:

Set-Cookie: PHPSESSID=4baf911e6cd84716755e705c61296fa0; path=/; secure; HttpOnly; SameSite=Lax

⚠️ Compared hashes and sessions started too late

TL;DR: Store the result of password_hash($password, PASSWORD_DEFAULT), not the password. The result is a hash: a one-way result that can be matched but never turned back into the password. In PHP 8.4 it is a 60-character bcrypt $2y$12$..., with a salt (random text) inside, so two hashes of the same password always differ. PASSWORD_ARGON2ID gives a 97-character $argon2id$..., so make the column VARCHAR(255). Match it with password_verify($input, $hash), never with ===, and renew old hashes with password_needs_rehash at login. A session lets PHP remember who logged in: session_start() (before any output) gives the browser a PHPSESSID cookie holding a random number, and keeps $_SESSION on the server. After a successful login, call session_regenerate_id(true) so an attacker can't use the session ID from before the login (session fixation). Set the cookie with session_set_cookie_params (secure, httponly, samesite) before session_start(). Log out with $_SESSION = [], session_destroy(), then delete the cookie.

⚡ Store the hash, not the password

Write:

<?php
$hash = password_hash("secret", PASSWORD_DEFAULT);
echo $hash;
Guess first: if password_hash("secret", ...) is called once more, is the result the same?

Different, because the salt (random text that goes into the hash) is new on every call. The password checker password_verify("secret", $hash) is still true for both, because the salt and the cost (the work factor) are stored inside the hash.

Meaning: password_hash turns a password into a hash: a string that can be matched but never turned back into the password. The result is a 60-character string like $2y$12$.... That string goes into the password column in the database, not the password. Make the column VARCHAR(255), so it still fits if the default algorithm changes.

⚡ Match it with password_verify

Meaning: password_verify($password, $hash) reads the algorithm, cost and salt from $hash, hashes the typed password again with the same settings, then compares the results. A hash can't be compared with ===, because every new hash brings a new salt.

⚡ A session remembers who logged in

Write:

<?php
session_start();
$_SESSION["user_id"] = 1;

Meaning: A session lets PHP remember who logged in on the next requests. session_start() gives the browser a random number (the session ID) in the PHPSESSID cookie, a small piece of data the browser sends again with every request. The contents of $_SESSION are stored on the server, per ID. session_start() must run before any output (text sent to the browser). After a successful login, call session_regenerate_id(true) so the session ID from before the login can't be used again.

What you will learn