While cookies store data locally on the user's browser, Sessions store application state and sensitive user records securely on the web server. When a visitor logs into their college student dashboard, shopping cart, or banking account, PHP establishes a session. Because session data never leaves the server, it is immune to client-side tampering, making it the backbone of modern web authentication.
session_start() is called, PHP generates a cryptographically random 32-character string called the Session ID (e.g. c8f49a1d2...).PHPSESSID.$_SESSION.PHPSESSID cookie, allowing PHP to instantly recognize the user.session_start() must be the very first statement on your page, before any HTML or output!
<?php
// Step 1: Initialize the session environment
session_start();
// Step 2: Store user authentication credentials in $_SESSION
$_SESSION["user_id"] = 1042;
$_SESSION["username"] = "vikram_aditya";
$_SESSION["role"] = "bca_student";
$_SESSION["login_time"] = time();
echo "Session initialized! User credentials stored securely on server.";
?>
On any other page on your website (e.g. dashboard.php), simply call session_start() to retrieve the active session variables:
<?php
session_start();
// Check if user is logged in
if (!isset($_SESSION["username"])) {
header("Location: login.php"); // Redirect unauthorized guest
exit();
}
echo "<h2>Welcome to your Dashboard, " . htmlspecialchars($_SESSION["username"]) . "!</h2>";
echo "<p>Your Role: " . $_SESSION["role"] . "</p>";
?>
To log a user out completely and clean up server memory, execute this 3-step logout sequence:
<?php
session_start();
// Step 1: Clear all session variables in memory
$_SESSION = [];
session_unset();
// Step 2: Expire the client-side session cookie
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Step 3: Destroy the server-side session storage file
session_destroy();
header("Location: login.php?msg=logged_out");
exit();
?>
session_regenerate_id()During user login, always regenerate the session ID to neutralize Session Fixation attacks:
<?php
session_start();
// After verifying username & password against database:
session_regenerate_id(true); // Generates new session ID and deletes old file!
$_SESSION['authenticated'] = true;
?>
High-Frequency Exam Question:
Q: Compare Cookies vs Sessions in terms of security and capacity.
A: Cookies store up to ~4KB of data on the client machine and are susceptible to client-side manipulation and XSS theft. Sessions store virtually unlimited data on the web server, protected behind a random 32-character token, providing enterprise-grade security.
Exercise 27.1: Build a two-page login and dashboard script where the user enters a username on page 1, and page 2 greets them with their session name.
Exercise 27.2: Implement a session inactivity timeout that automatically logs the user out if they remain inactive for more than 15 minutes.