Sessions & Cookies
PHPHTTP is stateless — each request is independent. Sessions and cookies allow you to persist data across multiple page requests, which is essential for user authentication.
Sessions
Sessions store data on the server. A session ID is stored in a cookie on the client.
PHP
<?php
// MUST be called before any output!
session_start();
// Set session data
$_SESSION["username"] = "john";
$_SESSION["user_id"] = 42;
$_SESSION["logged_in"] = true;
echo "Session started!";
?>Reading Session Data
PHP
<?php
session_start();
// Check if logged in
if (isset($_SESSION["logged_in"]) && $_SESSION["logged_in"] === true) {
$username = $_SESSION["username"];
echo "Welcome, $username!";
} else {
echo "Please log in.";
header("Location: login.php");
exit();
}
?>Destroying a Session (Logout)
PHP
<?php
session_start();
// Remove specific session variable
unset($_SESSION["username"]);
// Remove ALL session data
session_unset();
// Destroy the session completely (logout)
session_destroy();
header("Location: login.php");
exit();
?>Cookies
Cookies store data in the user's browser. They persist even after the browser is closed.
PHP
<?php
// Set a cookie (expires in 30 days)
setcookie(
"username", // name
"john", // value
time() + (30 * 24 * 60 * 60), // expiry
"/", // path
"", // domain
true, // secure (HTTPS only)
true // httponly (no JavaScript access)
);
// Read cookie
if (isset($_COOKIE["username"])) {
echo "Welcome back, " . $_COOKIE["username"];
}
// Delete cookie (set expiry in past)
setcookie("username", "", time() - 3600, "/");
?>Sessions vs Cookies
| Sessions | Cookies | |
|---|---|---|
| Storage | Server | Browser |
| Security | More secure | Less secure |
| Persistence | Until browser closes | Until expiry date |
| Size limit | No limit | 4KB max |
| Use for | Login state, cart | Remember me, preferences |
💡
Laravel handles sessions automatically! Use
session('key', 'value') to set and session('key') to get. Laravel also has flash messages: session()->flash('success', 'Saved!')Test your knowledge!
Take the PHP Basics quiz.