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 |
- In PHP 8.4,
PASSWORD_DEFAULT(PHP's default algorithm) is bcrypt with cost 12. Before PHP 8.4 the default cost was 10, so older hashes in the database start with$2y$10$. - The salt is random. So a second call to
password_hash("secret", ...)gives a different string, for example$2y$12$0fF4jsuAY9gEpGHfUcKStu/uxzz2XtPZ.... Even so, the password checkerpassword_verify("secret", $hash)is stilltruefor both, because the salt and cost are stored inside that string. PASSWORD_ARGON2IDuses Argon2id and its result is longer, 97 characters:$argon2id$v=19$m=65536,t=4,p=1$U0tjMFVZWndrRG9aOFBPTA$K8zx....mis memory in KB,tthe number of passes, andpthe number of lines of work that run at the same time.- Because the default algorithm can change in a later PHP version, make the column
VARCHAR(255), notCHAR(60).
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_verify($password, $hash)reads the algorithm, cost and salt from$hash. Then it hashes the typed password again with the same settings and compares the results."secret"matches,"Secret"doesn't (letter case counts).- A hash can't be compared with
===: a newpassword_hashalways brings a new salt, so the strings are never equal. - On a real login page, an unregistered email and a wrong password get the same sentence ("Wrong email or password"). If the sentences differ, outsiders can tell which emails have an account. This lesson's exercise keeps
User not foundandWrong passwordapart on purpose, so all three results can be checked: those two messages andLogin successful.
💡 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=/
session_start()reads thePHPSESSIDcookie from the browser. If there isn't one yet, PHP makes a random 32-character ID and sends it in aSet-Cookieheader.$_SESSIONis an array whose contents are stored on the server, per ID. With the default settings,$_SESSION["user_id"] = 1is saved as a filesess_058a66...holdinguser_id|i:1;.- On the next request, the browser sends the same cookie.
session_start()reads the file again, so$_SESSION["user_id"]holds 1. The browser only holds the number, like the numbered table card at Mrs. Tini's Stall. - Headers must be sent before the page content. So
session_start()must run before any output (any text or HTML sent to the browser). If output has already gone out, the result isWarning: session_start(): Session cannot be started after headers have already been sent.
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"];
}
- Before logging in, the browser already has a session ID. If that ID keeps being used after the login, anyone who already knew it is logged in as Budi too. For example, an attacker can slip that ID into the victim's browser before the victim logs in. This attack is called session fixation.
session_regenerate_id(true)makes a new ID and sends a newSet-Cookie. Thetrueargument deletes the old ID's data, so the old ID stops working.- Call it whenever the access level changes: on login, and on a password change. The attack in detail is in the lesson Session Management in the Security track, and the full login flow in the lesson Session-based Authentication in the Auth track.
💡 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
lifetime0: the cookie is gone when the browser closes.secure: only sent over HTTPS (an encrypted connection).httponly: JavaScript can't read it, so XSS code can't steal it.samesiteLax: not sent along with a POST from another site.session_set_cookie_paramsmust be called beforesession_start().- Logging out takes three steps: empty it with
$_SESSION = [];, destroy its data on the server withsession_destroy();, then delete the cookie withsetcookie(session_name(), "", time() - 3600, "/");. An expiry time one hour in the past (time() - 3600) makes the browser throw the cookie away.
⚠️ Compared hashes and sessions started too late
- Comparing hashes with
===or==. A new hash is always different because its salt is random. Usepassword_verify. - A password column that's too short. Argon2id needs 97 characters, and the default algorithm can change. Use
VARCHAR(255). - Passwords longer than 72 bytes. For plain letters, 1 letter is 1 byte. Bcrypt (
PASSWORD_DEFAULT) uses only the first 72 bytes and quietly drops the rest, with no error, in PHP 8.4 too. A hash of 72 lettersaplusXalso matches 72 lettersaplusY. Limit the length, for examplestrlen($password) <= 72, or usePASSWORD_ARGON2ID. - Forgetting
session_regenerate_id(true)after logging in. The same ID before and after the login opens a session fixation hole. session_start()after some output. The headers have already gone out, so the session can't start. Put it at the very top of the file.
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.