Lesson 4 of 8
Sessions - Stateful Authentication
HTTP is stateless - each request is independent. Sessions give PHP memory across requests by storing data server-side and giving the browser a session ID cookie. Sessions are fundamental for login systems, shopping carts, flash messages, and user preferences.
Sessions - Secure Configuration & Login Flow
<?php
declare(strict_types=1);
// ── Secure session configuration (call BEFORE session_start) ───
ini_set("session.use_strict_mode", "1"); // reject invalid session IDs
ini_set("session.cookie_httponly", "1"); // JS cannot access session cookie
ini_set("session.cookie_secure", "1"); // cookie only over HTTPS
ini_set("session.cookie_samesite", "Strict"); // CSRF protection
ini_set("session.gc_maxlifetime", "3600"); // 1 hour session lifetime
ini_set("session.use_only_cookies", "1"); // never pass session ID in URL
session_start();
// ── Login ──────────────────────────────────────────────────────
function loginUser(int $userId, string $role): void {
// CRITICAL: regenerate ID after login - prevents session fixation attacks
session_regenerate_id(true); // true = delete old session file
$_SESSION["user_id"] = $userId;
$_SESSION["role"] = $role;
$_SESSION["logged_in"] = true;
$_SESSION["login_time"] = time();
}
// ── Auth check middleware ──────────────────────────────────────
function requireLogin(): void {
if (!isset($_SESSION["logged_in"]) || $_SESSION["logged_in"] !== true) {
header("Location: /login?redirect=" . urlencode($_SERVER["REQUEST_URI"]));
exit;
}
// Session timeout check (30 min inactivity)
if (time() - ($_SESSION["last_activity"] ?? 0) > 1800) {
session_destroy();
header("Location: /login?timeout=1");
exit;
}
$_SESSION["last_activity"] = time();
}
function requireRole(string $role): void {
requireLogin();
if (($_SESSION["role"] ?? "") !== $role) {
http_response_code(403);
include __DIR__ . "/views/403.php";
exit;
}
}
// ── Using session data ─────────────────────────────────────────
requireLogin();
$userId = $_SESSION["user_id"];
$role = $_SESSION["role"];
// ── Flash messages (one-time messages across redirect) ─────────
function flashMessage(string $type, string $message): void {
$_SESSION["flash"][$type][] = $message;
}
function getFlashMessages(string $type): array {
$messages = $_SESSION["flash"][$type] ?? [];
unset($_SESSION["flash"][$type]); // consume - one-time only
return $messages;
}
// Set before redirect:
flashMessage("success", "Post created successfully!");
header("Location: /dashboard");
exit;
// Read on next page:
$successes = getFlashMessages("success");
$errors = getFlashMessages("error");
// ── Logout ─────────────────────────────────────────────────────
function logoutUser(): void {
// Clear session data
$_SESSION = [];
// Expire the session cookie
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), "", time() - 86400,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
session_destroy();
}Quick Quiz
Tip
Tip
Practice Sessions Stateful Authentication in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Sessions - Stateful Authentication
Practice Task
Note
Practice Task - (1) Write a working example of Sessions Stateful Authentication from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Sessions Stateful Authentication is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.
Finished this lesson?