PHP Sessions

PHP Sessions

Sessions store user data on the server. PHP links each user to their session data using a session ID stored in a cookie.

1 - Starting and Writing

<?php
session_start(); // must be before any output

$_SESSION["user_id"]  = 42;
$_SESSION["username"] = "Alice";
$_SESSION["role"]     = "admin";
?>

2 - Reading and Guarding

session_start();

if (!isset($_SESSION["user_id"])) {
    header("Location: /login.php");
    exit;
}

echo "Hello, " . htmlspecialchars($_SESSION["username"]);

3 - Destroying

session_start();
$_SESSION = [];           // wipe data
session_destroy();        // destroy on server
setcookie(session_name(), "", time() - 3600, "/"); // delete cookie

4 - Flash Messages

// Set (e.g. after redirect)
$_SESSION["flash"] = "Changes saved successfully!";

// Read and immediately remove
if (isset($_SESSION["flash"])) {
    echo "<div class=\"alert\">" . $_SESSION["flash"] . "</div>";
    unset($_SESSION["flash"]);
}

Note: Call session_regenerate_id(true) immediately after a successful login to prevent session fixation attacks, where a malicious actor forces a known session ID onto a victim before they log in.

-Tip-