PHP Sessions
What are PHP Sessions?
Section titled “What are PHP Sessions?”The HTTP protocol is stateless: the web server doesn’t remember anything about users between page requests. Each page load is like meeting a stranger.
- The Problem: When a user adds items to their shopping cart and navigates to another page, how does the server remember what’s in their cart?
- The Solution: PHP sessions let you store data on the server and associate it with a specific user. When the user visits different pages, the server uses a session ID to retrieve their data.
Unlike cookies (which store data in the browser), session data is stored securely on the server. Only a session ID is sent to the user’s browser as a cookie.
Common uses for sessions:
- User authentication: Keep users logged in as they navigate
- Shopping carts: Remember items users want to purchase
- User preferences: Store settings like theme or language
- Flash messages: Show one-time notifications after redirects
- Multi-step forms: Preserve data across form pages
How Sessions Work
Section titled “How Sessions Work”- Server creates a unique session ID
- Session ID sent to browser as a cookie
- Browser sends session ID with each request
- Server uses session ID to retrieve stored data
Starting a Session
Section titled “Starting a Session”Call session_start() at the very beginning of your PHP file, before any HTML output:
<?phpsession_start(); // Must be first thing in your PHP file?><!DOCTYPE html><html>...Adding Session Data
Section titled “Adding Session Data”Use the $_SESSION superglobal array to store data:
<?phpsession_start();
// Add single values$_SESSION['username'] = 'john_doe';$_SESSION['user_id'] = 123;$_SESSION['is_logged_in'] = true;
// Add arrays$_SESSION['cart'] = ['product1', 'product2'];$_SESSION['preferences'] = [ 'theme' => 'dark', 'language' => 'en'];?>Reading Session Data
Section titled “Reading Session Data”Always check if data exists before using it:
<?phpsession_start();
// Check if session data existsif (isset($_SESSION['username'])) { echo "Welcome, " . htmlspecialchars($_SESSION['username']);} else { echo "Please log in";}
// Get data with default value$theme = $_SESSION['theme'] ?? 'light';?>Removing Session Data
Section titled “Removing Session Data”Remove Specific Items
Section titled “Remove Specific Items”<?phpsession_start();
unset($_SESSION['cart']);unset($_SESSION['temp_data']);?>Complete Logout (Destroy Session)
Section titled “Complete Logout (Destroy Session)”<?phpsession_start();
// Clear all session variables$_SESSION = [];
// Delete the session cookieif (ini_get('session.use_cookies')) { $params = session_get_cookie_params(); setcookie(session_name(), '', time() - 3600, $params['path']);}
// Destroy the sessionsession_destroy();
// Redirect to login pageheader('Location: login.php');exit;?>Flash Messages
Section titled “Flash Messages”Flash messages are notifications that display once and then disappear. Useful for showing success/error messages after a redirect.
// Page 1: Set the flash message before redirecting$_SESSION['flash'] = 'Item added to cart!';header('Location: cart.php');exit;// Page 2: Display and remove the messagesession_start();
if (isset($_SESSION['flash'])) { echo '<div class="alert">' . htmlspecialchars($_SESSION['flash']) . '</div>'; unset($_SESSION['flash']); // Remove so it only shows once}Common Session Functions
Section titled “Common Session Functions”| Function | Purpose |
|---|---|
session_start() | Start or resume a session |
session_destroy() | Destroy all session data |
session_regenerate_id(true) | Generate new session ID (use after login) |
session_status() | Check if session is active (returns PHP_SESSION_ACTIVE, PHP_SESSION_NONE, or PHP_SESSION_DISABLED) |
session_unset() | Clear all session variables |
session_name() | Get/set the session name |
isset($_SESSION['key']) | Check if session variable exists |
unset($_SESSION['key']) | Remove specific session variable |
Session Timeout
Section titled “Session Timeout”Set an expiry time to automatically log out inactive users:
<?phpsession_start();
$timeout = 1800; // 30 minutes in seconds
// Check if session has expiredif (isset($_SESSION['last_activity'])) { if (time() - $_SESSION['last_activity'] > $timeout) { // Session expired - destroy and redirect session_unset(); session_destroy(); header('Location: login.php?expired=1'); exit; }}
// Update last activity time$_SESSION['last_activity'] = time();?>Session Security Tips
Section titled “Session Security Tips”-
Regenerate session ID after login to prevent session fixation:
session_regenerate_id(true); -
Use secure cookie settings:
ini_set('session.cookie_httponly', 1); // Prevent JavaScript accessini_set('session.cookie_secure', 1); // HTTPS only -
Always use HTTPS when handling sessions with sensitive data.
Example: Shopping Cart
Section titled “Example: Shopping Cart”<?phpsession_start();
// Initialize cart if it doesn't existif (!isset($_SESSION['cart'])) { $_SESSION['cart'] = [];}
// Add product to cartfunction addToCart($product_id) { $_SESSION['cart'][] = $product_id;}
// Remove product from cartfunction removeFromCart($product_id) { $key = array_search($product_id, $_SESSION['cart']); if ($key !== false) { unset($_SESSION['cart'][$key]); }}
// Get cart countfunction getCartCount() { return count($_SESSION['cart']);}?>