session_start(), $_SESSION, Security)Sessions preserve user state, authentication tokens, and temporary data across multiple page requests on a web application. Unlike cookies stored on the client browser, session payload data is stored securely on the web server, mapped to a unique Session ID sent to the browser via a cookie (PHPSESSID).
flowchart TD
A["User Requests Page"] --> B["session_start() Invoked"]
B --> C{"Check PHPSESSID Cookie"}
C -- Exists --> D["Load Server Session File into $_SESSION"]
C -- Missing --> E["Generate New Session ID & Set PHPSESSID Cookie"]
D & E --> F["Script Modifies $_SESSION Array"]
F --> G["Session Serialized to Server Storage on Script Finish"]
session_start(): Initializes or resumes session state (must be called before any HTML output!).session_regenerate_id(true): Generates new session ID and deletes old session file (prevents Session Fixation attacks).session_unset(): Clears all variables in $_SESSION array.session_destroy(): Destroys session data on server.<?php
declare(strict_types=1);
// Configure session cookie security flags before starting session
ini_set('session.cookie_httponly', '1');
ini_set('session.use_only_cookies', '1');
ini_set('session.cookie_samesite', 'Lax');
// Start or resume session
session_start();
// 1. Authenticate User & Regenerate ID
function loginUser(int $userId, string $username): void
{
// Prevent Session Fixation attack on login!
session_regenerate_id(true);
$_SESSION['user_id'] = $userId;
$_SESSION['username'] = $username;
$_SESSION['login_time'] = time();
}
// 2. Logout & Destroy Session
function logoutUser(): void
{
$_SESSION = [];
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(
session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
session_destroy();
}
// Test Session State
if (!isset($_SESSION['user_id'])) {
loginUser(101, "maksudur");
echo "User Logged In! Session ID Regenerated.
";
} else {
echo "Welcome Back, " . htmlspecialchars($_SESSION['username']) . "!
";
}
session_start() at Bootstrap Header: Execute session_start() before any whitespace or HTML headers are output to HTTP stream.session_regenerate_id(true) during logins, logouts, and password changes.$_SESSION: Sanitize outputs when rendering session values in HTML views.Write a function isLoggedIn(): bool that returns true if $_SESSION['user_id'] is set!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.