PHP Tutorial · PHP for the Web · Lesson 24 of 38
PHP Cookies and Sessions
Remember users between requests with cookies and sessions.
Cookies
A cookie is a small piece of data stored in the browser and sent back with every request. Set it before any output:
<?php
setcookie("theme", "dark", [
"expires" => time() + 60 * 60 * 24 * 30, // 30 days
"path" => "/",
"secure" => true, // HTTPS only
"httponly" => true, // not readable from JavaScript
"samesite" => "Lax",
]);
$theme = $_COOKIE["theme"] ?? "light";
Sessions
Sessions store data on the server; the browser only keeps a random session ID cookie. Use them for logins and shopping carts:
<?php
session_start(); // before any output
$_SESSION["user_id"] = 42; // after a successful login
$_SESSION["cart"][] = "book";
if (!isset($_SESSION["user_id"])) {
header("Location: /login.php");
exit;
}
// Logging out
session_regenerate_id(true);
$_SESSION = [];
session_destroy();
Call session_regenerate_id(true) after login to prevent session fixation attacks.
How a cart works
$_SESSION is just an array that PHP saves between requests. This example simulates two requests:
<?php
function addToCart(array &$session, string $item, int $qty = 1): void
{
$session["cart"][$item] = ($session["cart"][$item] ?? 0) + $qty;
}
$session = []; // request 1: empty session
addToCart($session, "book");
addToCart($session, "pen", 3);
$saved = serialize($session); // PHP stores the session between requests
$session = unserialize($saved); // request 2: session restored
addToCart($session, "book");
print_r($session["cart"]);
Output
Array
(
[book] => 2
[pen] => 3
)Test yourself
Where is session data stored?
In the browserOn the serverIn the URLIn a hidden form field
Show answer
Answer: On the server