Sessions, Login & Password Hashing
By the end of this lesson ShikshaPortal will have a staff login. Passwords will be stored as slow one-way hashes, the session cookie will carry safe settings, the session id will change at login, and every student page will check who is asking. Teachers will be able to view and correct records, and only admins will add, mark as left or delete.
What you should know first: Sessions & Cookies explains session_start() and $_SESSION, and Secure Login & Password Reset covers the PHP functions in more depth. You also need the student pages from CRUD with Prepared Statements.
How a session remembers you
HTTP forgets everything between requests. A session is PHP's way of remembering a visitor. Think of the cloakroom at Lucknow Charbagh station. You hand over your bag and get a small token with a number. The bag stays at the counter; you carry only the token. Next time, you show the token and get the same bag.
In PHP, the "bag" is a small file on the server, and the "token" is a cookie holding a random session id. This is a real session file from our test server after Neha logged in:
last_seen|i:1794808614;user|a:3:{s:2:"id";i:1;s:4:"name";s:11:"Neha Saxena";s:4:"role";s:5:"admin";}flash|a:1:{i:0;s:21:"Welcome, Neha Saxena.";}The browser never sees this data. It only sends the id back. That has a serious consequence: anyone who has the id is logged in as Neha. Most of this lesson is about keeping that id secret and short-lived.
Step 1: store hashes, never passwords
A hash is a one-way fingerprint of a password. You can check a password against it, but you cannot turn it back into the password. If the users table ever leaks, the attacker gets fingerprints, not passwords.
PHP does the hard parts for you. password_hash() adds a random salt (so two people with the same password get different hashes) and is deliberately slow. password_verify() checks a password against a stored hash:
<?php
declare(strict_types=1);
$password = 'Shiksha@Dev2026';
$hash = password_hash($password, PASSWORD_DEFAULT);
echo $hash, "\n";
echo strlen($hash), " characters\n";
var_dump(password_verify($password, $hash));
var_dump(password_verify('shiksha@dev2026', $hash));
$start = hrtime(true);
password_verify($password, $hash);
printf("One check took %d ms\n", (hrtime(true) - $start) / 1_000_000);$2y$12$tYUzTE.jeeoYqdQ0z2ha0ufWQhC57kBX8MHiwUF7N9RwC7Y0jfEJy 60 characters bool(true) bool(false) One check took 594 ms
Read the hash from the left: $2y$ means bcrypt, 12 is the cost, then come the salt and the result. Since PHP 8.4, PASSWORD_DEFAULT is bcrypt with cost 12 (it was 10 before). The slowness is the point: one check took over half a second on our busy test laptop, so an attacker with a stolen table can try only a few guesses per second per CPU core. The exact time depends on the machine.
The password_hash column in users is VARCHAR(255), as the database design planned, so a future default algorithm with longer hashes still fits. PASSWORD_ARGON2ID is also available when PHP is built with Argon2 support (our XAMPP build had it); bcrypt is a fine default.
Step 2: user accounts
database/seed.sql now ends with two development logins. The hashes were made by password_hash(); both passwords are Shiksha@Dev2026:
-- Development logins only. Both passwords are Shiksha@Dev2026.
-- On a real server, create users with bin/create-user.php instead.
INSERT INTO users (id, name, email, password_hash, role) VALUES
(1, 'Neha Saxena', 'neha@shiksha.test', '$2y$12$f8n6hrVvMF/zz2bsbrydZuAkLBkcRg8gHiEnlmZB82Q4LnUCJirKe', 'admin'),
(2, 'Vikram Yadav', 'vikram@shiksha.test', '$2y$12$LZ6Detkc3Pp9M4YZ3FE7tOxPVFq5ZV7usfz4J9cj8puhzolesDe6a', 'teacher');A live server must never have a known password, so real staff accounts come from a small script, bin/create-user.php. It reads the password from the keyboard instead of the command line, because command-line arguments are saved in your shell history and are visible to other users in the process list:
[, $email, $role, $name] = $argv + [null, '', '', ''];
if (!filter_var($email, FILTER_VALIDATE_EMAIL) || !in_array($role, ['admin', 'teacher'], true) || $name === '') {
exit("Usage: php bin/create-user.php <email> <admin|teacher> \"<name>\"\n");
}
echo 'Password (at least 12 characters): ';
$hide = PHP_OS_FAMILY !== 'Windows' && stream_isatty(STDIN);
if ($hide) {
shell_exec('stty -echo'); // do not show the password while typing
}
$password = rtrim((string) fgets(STDIN), "\r\n");
if ($hide) {
shell_exec('stty echo');
}
if (mb_strlen($password) < 12) {
exit("\nToo short. Nothing was saved.\n");
}
$stmt = db()->prepare(
'INSERT INTO users (name, email, password_hash, role) VALUES (:name, :email, :hash, :role)'
);
$stmt->execute([
'name' => $name, 'email' => strtolower($email),
'hash' => password_hash($password, PASSWORD_DEFAULT), 'role' => $role,
]);
echo "\nCreated user " . db()->lastInsertId() . " ({$role}).\n";php bin/create-user.php kiran.joshi@shiksha.test teacher "Kiran Joshi"Password (at least 12 characters): Created user 3 (teacher).
The app user shiksha_app can run this INSERT, because it has the four data rights. Length matters more than odd symbols, so the script asks for at least 12 characters.
Step 3: start the session safely
All the session and login code goes in a new file, src/auth.php, loaded by src/bootstrap.php. Sessions are for web requests only, so public/index.php calls start_session(); right after the bootstrap, and the bin/ scripts never start one.
function start_session(): void
{
session_name('shiksha_sid');
session_start([
'cookie_httponly' => true,
'cookie_secure' => str_starts_with(config('app')['url'], 'https://'),
'cookie_samesite' => 'Lax',
'use_strict_mode' => true,
]);
// Log out anyone who has been idle for 30 minutes
$now = time();
if (isset($_SESSION['last_seen']) && $now - $_SESSION['last_seen'] > 1800) {
$_SESSION = [];
session_regenerate_id(true);
}
$_SESSION['last_seen'] = $now;
}| Setting | What it does | What it stops |
|---|---|---|
cookie_httponly | JavaScript cannot read the cookie | A script injected through an XSS bug stealing the id |
cookie_secure | The cookie is sent only over HTTPS | The id leaking on public Wi-Fi. On when APP_URL starts with https:// |
cookie_samesite = Lax | Not sent with cross-site POSTs | Another site submitting forms as your logged-in user |
use_strict_mode | PHP refuses ids it did not create | Session fixation (below) |
The last lines of start_session() empty the session after 30 minutes without a request, which matters on a shared staff-room computer. The custom name shiksha_sid replaces the default PHPSESSID, so the cookie does not advertise PHP. The real header from our server:
Set-Cookie: shiksha_sid=399d83586fe12737ff1ead5414e16856; path=/; HttpOnly; SameSite=Lax
There is no secure flag yet because our local APP_URL is http://shiksha.test; HTTPS comes with Deploying to a Linux Server, and then the flag turns on by itself.
use_strict_mode is off by default in PHP. We tested why that matters. With it off, we sent a made-up cookie, shiksha_sid=chosenbyattacker123. PHP created a session file named sess_chosenbyattacker123 and used it. That is session fixation: an attacker plants an id they know in a victim's browser, waits for the victim to log in, then uses the same id. With strict mode on, the same request got a brand-new random id in a Set-Cookie header instead.
Step 4: log in and log out
Three functions in src/auth.php do the work:
function attempt_login(string $email, string $password): ?array
{
$stmt = db()->prepare(
'SELECT id, name, role, password_hash FROM users WHERE email = :email'
);
$stmt->execute(['email' => $email]);
$user = $stmt->fetch();
if ($user === false) {
password_verify($password, DUMMY_HASH); // same delay as a real check
return null;
}
if (!password_verify($password, $user['password_hash'])) {
return null;
}
if (password_needs_rehash($user['password_hash'], PASSWORD_DEFAULT)) {
$update = db()->prepare('UPDATE users SET password_hash = :hash WHERE id = :id');
$update->execute(['hash' => password_hash($password, PASSWORD_DEFAULT), 'id' => $user['id']]);
}
return $user;
}
function login_user(array $user): void
{
session_regenerate_id(true); // a fresh id after login stops session fixation
$_SESSION['user'] = ['id' => $user['id'], 'name' => $user['name'], 'role' => $user['role']];
}
function logout_user(): void
{
$_SESSION = [];
$cookie = session_get_cookie_params();
unset($cookie['lifetime']); // setcookie() wants 'expires' instead
setcookie(session_name(), '', ['expires' => time() - 3600] + $cookie);
session_destroy();
}Some details that are easy to miss:
- One message for both mistakes. A wrong email and a wrong password both show "Email or password is wrong." Different messages would let anyone find out which staff emails exist.
DUMMY_HASHis a constant holding a real bcrypt hash. Checking against it when the email is unknown makes both failures take about the same time, so the response time does not give the answer away either.password_needs_rehash()upgrades old hashes. A hash made with cost 10 is replaced by a cost-12 hash the next time that person logs in.session_regenerate_id(true)gives a new id and deletes the old session file. Even if an attacker knew the old id, it is now useless.
The routes in public/index.php are short: GET /login shows the form, POST /login calls attempt_login(), then login_user(), flash() and redirect(), and POST /logout calls logout_user() and redirects to /login. Logout is a POST form, so a link on another site cannot log your staff out. Here is a wrong password, then the right one, with the same cookie jar:
HTTP/1.1 422 Unknown Status Code
Set-Cookie: shiksha_sid=efefbc625b907ce7275a39f8ce414918; path=/; HttpOnly; SameSite=Lax
<p class="error" role="alert">Email or password is wrong.</p>
HTTP/1.1 303 See Other
Set-Cookie: shiksha_sid=2ea1d9e2850e078aeff2295f0eed06ed; path=/; HttpOnly; SameSite=Lax
Location: /students?class_id=3The id changed from efefbc... to 2ea1d9... at the moment of login. ("Unknown Status Code" is just how PHP's built-in server, used for this test, names status 422; the number is what matters.) This is how the login form looks to the browser. Fill it in and press the button: the script shows what a method="get" form would have done with the password.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Staff login</title>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; }
label { display: block; font-weight: 600; }
pre { background: #f4f4f4; padding: 8px; white-space: pre-wrap; }
</style>
</head>
<body>
<h1>Staff login</h1>
<form id="login" method="post" action="/login">
<input type="hidden" name="next" value="/students?class_id=3">
<p><label for="email">Email</label>
<input id="email" name="email" type="email" value="neha@shiksha.test" autocomplete="username" required></p>
<p><label for="password">Password</label>
<input id="password" name="password" type="password" autocomplete="current-password" required></p>
<button>Log in</button>
</form>
<pre id="out"></pre>
<script>
document.querySelector("#login").addEventListener("submit", (event) => {
event.preventDefault();
const query = new URLSearchParams(new FormData(event.target)).toString();
document.querySelector("#out").textContent =
"With method=\"post\" the fields travel in the request body.\n\n" +
"With method=\"get\" the browser would open this address, and the password\n" +
"would land in the history, server access logs and Referer headers:\n\n" +
"http://shiksha.test/login?" + query;
});
</script>
</body>
</html>The autocomplete="username" and "current-password" values help password managers fill the right fields.
Step 5: protect pages with roles
Two more helpers guard the routes. require_login() sends visitors to the login page and stops anyone whose role is not allowed:
function require_login(string ...$roles): array
{
$user = current_user(); // $_SESSION['user'] ?? null
if ($user === null) {
redirect('/login?next=' . rawurlencode($_SERVER['REQUEST_URI'] ?? '/'));
}
if ($roles !== [] && !in_array($user['role'], $roles, true)) {
http_response_code(403);
render('error', ['title' => 'Not allowed', 'message' => 'Your account cannot do this.']);
exit;
}
return $user;
}
/** Only allow redirects to paths on this site, never to another website. */
function safe_next(mixed $next): string
{
return is_string($next) && preg_match('#^/(?![/\\\\])\S*$#', $next) ? $next : '/';
}Each student route now starts with one line: require_login(); for listing, viewing and editing, and require_login('admin'); for adding, marking as left and deleting. Class lists stay public. Student pages hold children's dates of birth and parents' phone numbers, so they must never be open to the internet. Logged in as Vikram, a teacher, our server answered:
GET /students 200 GET /student/edit?id=5 200 GET /students/new 403 POST /student/leave?id=5 403
safe_next() closes an open redirect. Without it, a phishing email could link to /login?next=https://evil.example/ and your own login page would send staff to a fake site after a real login. The pattern accepts only paths that start with one /. Browsers treat //evil.example and /\evil.example as other websites, so both are refused. Our tests: /students?class_id=3 was kept, and https://evil.example/, //evil.example/login and /\evil.example all became Location: /.
Finally, templates/layout.php shows the logged-in name with a "Log out" button, and prints one-time flash messages such as "Welcome, Neha Saxena." flash() stores a message in $_SESSION['flash']; take_flashes() returns it and removes it, so it appears exactly once, on the page after the redirect.
Common mistakes
- Not regenerating the session id at login. Session fixation stays possible. Call
session_regenerate_id(true). - Leaving
use_strict_modeoff. PHP then accepts ids chosen by an attacker. - Telling users "no such email". It reveals which accounts exist. Use one message.
- Redirecting to any
nextvalue. That is an open redirect. Allow only local paths. - Hiding admin buttons but not checking on the server. Anyone can send the POST with
curl. Check the role in the route.
Login forms also attract password guessing, so limit repeated attempts as part of Security Hardening for LAMP. The login and logout forms also need CSRF tokens, the subject of Forms, Validation & CSRF.
Interview questions
1. Why hash passwords instead of encrypting them?
Encryption can be reversed by anyone with the key, and the key usually sits on the same server. A password hash is one-way: the app only needs to check a guess, never to read the password. Slow, salted hashes like bcrypt also make guessing from a stolen table expensive.
2. What is session fixation and how do you prevent it?
The attacker gets the victim to use a session id the attacker already knows, then waits for the victim to log in with it. Prevent it with session.use_strict_mode so PHP rejects ids it did not create, and call session_regenerate_id(true) whenever a user logs in or changes privilege.
3. What do the HttpOnly, Secure and SameSite cookie attributes do?
HttpOnly hides the cookie from JavaScript, which limits damage from XSS. Secure sends it only over HTTPS. SameSite=Lax stops the browser sending it with cross-site POST requests, which blocks many CSRF attacks while still allowing normal links into the site.
4. Why is checking the role in the template not enough?
Templates only decide what is shown. An attacker can send the request directly, so every route that changes data must check the user's role on the server before acting.
Key points
- A session is a server-side store; the cookie carries only a random id, so guard the id.
- Store
password_hash()output (bcrypt, cost 12 by default since PHP 8.4) and check withpassword_verify(). - Start sessions with HttpOnly, SameSite=Lax, strict mode, and Secure on HTTPS.
- Regenerate the id at login; log out with a POST that clears the data and the cookie.
- Use one error message for wrong email or password, and a dummy hash to even out timing.
- Check login and role in every route with
require_login(), and allow only localnextpaths.
Exercise
Add a "Change password" page for logged-in staff at GET and POST /account/password. The form asks for the current password and the new one twice. Check the current password with password_verify(), require at least 12 characters and matching new passwords, save a new hash, and call session_regenerate_id(true). Show "Password changed." as a flash message after a 303 redirect.
Show solution
'POST /account/password' => function (): void {
$user = require_login();
$current = (string) ($_POST['current'] ?? '');
$new = (string) ($_POST['new'] ?? '');
$repeat = (string) ($_POST['repeat'] ?? '');
$stmt = db()->prepare('SELECT password_hash FROM users WHERE id = :id');
$stmt->execute(['id' => $user['id']]);
$hash = (string) $stmt->fetchColumn();
$error = match (true) {
!password_verify($current, $hash) => 'Your current password is wrong.',
mb_strlen($new) < 12 => 'Use at least 12 characters.',
$new !== $repeat => 'The new passwords do not match.',
default => null,
};
if ($error !== null) {
http_response_code(422);
render('account-password', ['title' => 'Change password', 'error' => $error]);
return;
}
$update = db()->prepare('UPDATE users SET password_hash = :hash WHERE id = :id');
$update->execute(['hash' => password_hash($new, PASSWORD_DEFAULT), 'id' => $user['id']]);
session_regenerate_id(true);
flash('Password changed.');
redirect('/');
},Asking for the current password stops someone who finds an unlocked, logged-in computer from taking over the account. A new session id after the change means an old stolen id stops working.
Quick Quiz
1. What does the browser store for a ShikshaPortal login?
The session data stays on the server; the cookie is just the token.
2. Which PHP setting makes the server refuse session ids it did not create?
Strict mode blocks session fixation with made-up ids.
3. A login link has next=//evil.example/. Where does ShikshaPortal redirect after login?
safe_next() allows only paths that begin with a single slash.
4. Why does attempt_login() call password_verify() even when the email does not exist?
Equal timing stops attackers from discovering which emails are real.
Learn LAMP Stack with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
