Login with sessions
A login proves that a visitor knows a password without ever storing that password. In PHP the hash functions do the checking, and the session remembers the result.
password_hash and verify
Passwords are never stored as plain text. A hash is a one-way fingerprint: easy to compute, practically impossible to reverse. PHP computes it with password_hash() and checks a login attempt with password_verify() - the function compares, never you.
The second argument is the algorithm. PASSWORD_DEFAULT tracks the current best choice, so hashes stay strong without code changes. Store the full result in one text column - it already carries the algorithm, the cost, and the salt.
<?php $password = "correct horse"; $hash = password_hash($password, PASSWORD_DEFAULT); if (password_verify($password, $hash)) { echo "Welcome back", PHP_EOL; } if (!password_verify("guess", $hash)) { echo "Wrong password", PHP_EOL; }
php hash.php
Welcome back
Wrong password
The right password passes and the wrong one fails, so the two calls do the whole check. The hash itself is different on every run, because PASSWORD_DEFAULT adds a fresh salt each time, which is why this page shows the result of the check and not the hash.
A login sketch
A login script does four things in order: start the session, load the user row by name, verify the password, and only then mark the session as logged in. The first step is session_start(). Anything else - greeting the user, loading settings - waits until after the check.
On success, rotate the session id with session_regenerate_id(true) so an id seen before login cannot be reused after it. Then store the user id and redirect. The full login flow is covered in Authentication and Authorization in PHP 8.
The file login.php in the folder you serve with php -S 127.0.0.1:8000, with the row loaded from the database in its place:
<?php $row = ["id" => 7, "hash" => password_hash("secret", PASSWORD_DEFAULT)]; $password = "secret"; session_start(); if (password_verify($password, $row["hash"])) { session_regenerate_id(true); $_SESSION["user_id"] = (int) $row["id"]; header("Location: /dashboard.php"); exit; }
curl -s -o /dev/null -w "%{http_code}" "http://127.0.0.1:8000/login.php"
302
The successful check answers with a redirect and the page tells the client where to go next with its Location header. A wrong password skips the whole block, because nothing inside the if runs.
Guard pages
Every protected page repeats the same two lines: start the session, then demand a logged-in marker. Put the check at the very top, before any output - headers and redirects stop working once the page starts printing.
The file guard.php in the same folder:
<?php session_start(); if (!isset($_SESSION["user_id"])) { header("Location: /login.php"); exit; }
curl -s -o /dev/null -w "%{http_code}" "http://127.0.0.1:8000/guard.php"
302
A visitor without a session is sent to the login page before any content is built. The same request with a logged-in session skips the block and the page body follows.
Logout
Logout reverses login: empty the session array, destroy the session on the server, and send the user back to the login page. Destroying without emptying, or emptying without destroying, leaves half a session behind - which is how ghost logins happen.
The file logout.php in the same folder:
<?php session_start(); $_SESSION = []; session_destroy(); header("Location: /login.php"); exit;
curl -s -o /dev/null -w "%{http_code}" "http://127.0.0.1:8000/logout.php"
302
The answer is the redirect to the login page, and the session data is gone before the client asks for it. A logout that only empties the array would leave the record on the server and the cookie in the browser.
Exercises
- Change the password in hash.php to a wrong one and run it. Which line appears?
- Print password_get_info($hash)["algoName"] and find the current default algorithm.
- Add a second user row to login.php and log in as each of them.
- Request guard.php with the session cookie of login.php. Which answer do you get now?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
password_hash()return?Answer
A one-way hash that carries the algorithm, the cost and the salt
The whole result is one text value that password_verify can read back, salt and cost included.
-
What does
password_verify()take?Answer
The password and the stored hash
The function hashes the attempt with the salt of the stored value and compares the two.
-
Why use
password_verify()instead of comparing two hashes with===?Answer
It compares in constant time and reads the format of the stored hash
A constant time comparison does not leak how much of the value matched, and the format is handled for you.
-
What does a protected page check first?
Answer
$_SESSION["user_id"]aftersession_start()The logged-in marker is the user id in the session, and the check runs before any output.
-
What does this program print?
<?php $hash = password_hash("secret", PASSWORD_DEFAULT); var_dump(password_verify("secret", $hash));Answer
bool(true)
The attempt matches the value the hash was built from, so verify returns true.
-
What does this program print?
<?php $hash = password_hash("secret", PASSWORD_DEFAULT); var_dump(password_verify("guess", $hash));Answer
bool(false)
The attempt does not match the hashed password, so the check fails.
-
What does this program print?
<?php $hash = password_hash("secret", PASSWORD_DEFAULT); var_dump($hash === "secret");Answer
bool(false)
A hash is not the password, so the strict comparison with the plain text is false.
-
What does this program print?
<?php $hash = password_hash("secret", PASSWORD_DEFAULT); var_dump(password_get_info($hash)["algoName"]);Answer
string(6) "bcrypt"
The current default of PHP 8.5 is bcrypt, and the hash carries its own algorithm name.
-
Why is a column of plain-text passwords dangerous?
Answer
A leak of the table exposes every password at once
Hashes make a leak far less useful, because the original passwords do not leave with the table.
-
What happens right before the user id is stored in the session?
Answer
The session id is regenerated
The fresh id takes a planted one out of use at the moment the account is trusted.
The code on this page was run with PHP 8.5.13 (php -v) in Alpine Linux, with the commands shown above.
Article author: Arthur Isaev