Remember your visitors from page to page: secure login, a session-based shopping cart, and properly protected cookies.
Open this lesson in KodokonHTTP remembers nothing: each request arrives fresh, with no link to the previous one. Sessions solve this problem: session_start() associates the visitor with a unique identifier, transmitted in a cookie, and a storage space on the server side accessible via $_SESSION. Call session_start() right at the top of every relevant page, before any output.
<?php
declare(strict_types=1);
session_start();
$storedHash = password_hash('secret123', PASSWORD_DEFAULT);
$password = $_POST['password'] ?? '';
if (password_verify($password, $storedHash)) {
session_regenerate_id(true);
$_SESSION['user_id'] = 42;
header('Location: /account.php');
exit;
}
echo "Invalid credentials.";Protecting a page comes down to checking the user's presence in the session, and redirecting otherwise. The session also serves as the ideal temporary storage for a shopping cart: an associative array product id => quantity survives from page to page.
<?php
declare(strict_types=1);
session_start();
if (!isset($_SESSION['user_id'])) {
header('Location: /login.php');
exit;
}
$_SESSION['cart'] ??= [];
$productId = filter_input(
INPUT_POST,
'product_id',
FILTER_VALIDATE_INT
);
if (is_int($productId)) {
$qty = $_SESSION['cart'][$productId] ?? 0;
$_SESSION['cart'][$productId] = $qty + 1;
}
$count = array_sum($_SESSION['cart']);
echo "Cart: " . $count . " item(s)";Cookies, on the other hand, live on the user's device and survive closing the browser: perfect for a theme or a language preference. Since PHP 7.3, setcookie() accepts an array of options: require secure (HTTPS only), httponly (invisible to JavaScript), and samesite (limits sending from other sites).
<?php
setcookie('theme', 'dark', [
'expires' => time() + 60 * 60 * 24 * 30,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
]);
$theme = $_COOKIE['theme'] ?? 'light';
echo "Active theme: " . $theme;Logging out must be as carefully done as logging in: empty $_SESSION, destroy the session on the server side, and expire the cookie that carried the identifier.
<?php
session_start();
$_SESSION = [];
session_destroy();
setcookie(session_name(), '', time() - 3600, '/');
header('Location: /login.php');
exit;