Sessions store user data on the server. PHP links each user to their session data using a session ID stored in a cookie.
<?php
session_start(); // must be before any output
$_SESSION["user_id"] = 42;
$_SESSION["username"] = "Alice";
$_SESSION["role"] = "admin";
?>
session_start();
if (!isset($_SESSION["user_id"])) {
header("Location: /login.php");
exit;
}
echo "Hello, " . htmlspecialchars($_SESSION["username"]);
session_start();
$_SESSION = []; // wipe data
session_destroy(); // destroy on server
setcookie(session_name(), "", time() - 3600, "/"); // delete cookie
// 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"]);
}