Sessions and cookies
HTTP has no memory: each request arrives alone and the server does not know the previous one came from the same user. To remember who has logged in, what is in their cart or which message must be shown only once, we need a state mechanism. Cookies store small pieces of data in the browser, and sessions store the data on the server and give the browser only an identifier. Understanding the difference well is the base of any login system.
Cookies
A cookie is created by the server with setcookie() and the browser sends it back on every request; it arrives in $_COOKIE. Since the user can read and modify their cookies, never store sensitive data or security decisions in them (such as "isAdmin=1"). Use the protection attributes: httponly prevents JavaScript from reading it (blocks theft through XSS), secure limits it to HTTPS and samesite restricts it to same-site requests (blocks CSRF). setcookie must be called before any output is sent.
<?php
declare(strict_types=1);
// Remember the preferred theme for 30 days (not sensitive data)
$allowed = ['light', 'dark'];
$requested = $_GET['theme'] ?? '';
if (in_array($requested, $allowed, true)) {
setcookie('theme', $requested, [
'expires' => time() + 60 * 60 * 24 * 30,
'path' => '/',
'secure' => false, // set true when the site uses HTTPS
'httponly' => true,
'samesite' => 'Lax',
]);
$theme = $requested;
} else {
$theme = in_array($_COOKIE['theme'] ?? '', $allowed, true) ? $_COOKIE['theme'] : 'light';
}
echo 'Current theme: ', htmlspecialchars($theme, ENT_QUOTES, 'UTF-8'), "\n";Sessions
With session_start() PHP creates or recovers a session: it generates a random identifier, sends it to the browser in a cookie (PHPSESSID) and gives you the $_SESSION array, whose content is stored on the server. It must be called before any output. Store only what is necessary there, such as the user id, and read the rest again from the database. Configure the session cookie with session_set_cookie_params before session_start: httponly, samesite and secure in production.
<?php
// File: src/session.php
declare(strict_types=1);
function startSession(): void
{
if (session_status() === PHP_SESSION_ACTIVE) {
return;
}
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
'secure' => !empty($_SERVER['HTTPS']),
'httponly' => true,
'samesite' => 'Lax',
]);
session_start();
}
function flash(string $message): void
{
$_SESSION['flash'] = $message;
}
function takeFlash(): ?string
{
$message = $_SESSION['flash'] ?? null;
unset($_SESSION['flash']); // shown only once
return is_string($message) ? $message : null;
}
function logout(): void
{
$_SESSION = [];
if (ini_get('session.use_cookies')) {
$p = session_get_cookie_params();
setcookie(session_name(), '', time() - 3600, $p['path'], $p['domain'], $p['secure'], $p['httponly']);
}
session_destroy();
}Two session-specific attacks deserve attention. In session fixation, the attacker makes the victim use an identifier they already know; the defense is to call session_regenerate_id(true) right after a successful login, which changes the identifier. In session theft, the attacker obtains the identifier through XSS or an insecure network; the defenses are httponly, HTTPS and escaping output. When logging out, empty $_SESSION, delete the cookie and destroy the session, as the logout() function above does.
<?php
// File: counter.php (run with: php -S localhost:8000)
declare(strict_types=1);
require_once __DIR__ . '/src/session.php';
startSession();
$_SESSION['visits'] = ($_SESSION['visits'] ?? 0) + 1;
header('Content-Type: text/plain; charset=utf-8');
echo "You have visited this page {$_SESSION['visits']} times.\n";Choose well where to store the session files and how long they last. By default PHP keeps them in temporary files on the server and deletes them after the time configured in session.gc_maxlifetime. For a shop or a bank you will want short sessions with renewal; for a blog, a longer lifetime is enough. On servers with several machines, sessions are usually stored in a database or in Redis so all machines share them.
Teste dein Wissen
Frage 1 von 1Where is the $_SESSION data stored?
✎ Meine Notizen
Nur in diesem Browser gespeichert. Melde dich an, um es im Konto zu behalten.0/5000 Zeichen