Sessions and Cookies in php
Sessions and cookies help maintain state across multiple HTTP requests since HTTP is stateless by default.
Cookies
A cookie is a small text file stored on the client's browser.
Setting a Cookie
<?php
// setcookie(name, value, expiry, path, domain, secure, httponly)
setcookie("username", "Alice", time() + 86400, "/"); // expires in 1 day
setcookie("theme", "dark", time() + (30 * 86400)); // expires in 30 days
?>
Note: setcookie() must be called before any HTML output.
Reading a Cookie
<?php
if (isset($_COOKIE['username'])) {
echo "Welcome, " . htmlspecialchars($_COOKIE['username']);
} else {
echo "Cookie not set.";
}
?>
Deleting a Cookie
Set the expiry to a time in the past:
<?php
setcookie("username", "", time() - 3600, "/"); // expire 1 hour ago
?>
Cookie Options (php 7.3+)
<?php
setcookie("token", "abc123", [
"expires" => time() + 86400,
"path" => "/",
"secure" => true, // HTTPS only
"httponly" => true, // not accessible via JavaScript
"samesite" => "Strict" // CSRF protection
]);
?>
Sessions
A session stores data on the server and uses a cookie to link the browser to the session data.
Starting a Session
<?php
session_start(); // must be called before any output
?>
Storing Session Data
<?php
session_start();
$_SESSION['user_id'] = 101;
$_SESSION['username'] = "Alice";
$_SESSION['role'] = "admin";
echo "Session started for " . $_SESSION['username'];
?>
Reading Session Data
<?php
session_start();
if (isset($_SESSION['username'])) {
echo "Logged in as: " . $_SESSION['username'];
} else {
echo "Not logged in.";
header("Location: login.php");
exit;
}
?>
Modifying Session Data
<?php
session_start();
$_SESSION['visits'] = ($_SESSION['visits'] ?? 0) + 1;
echo "Visit count: " . $_SESSION['visits'];
?>