PHP Sessions
What are PHP Sessions?
Section titled “What are PHP Sessions?”The HTTP protocol is stateless: that means 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
- 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”- To be able to store data in a session, you need to start a session or resume a session by calling the session_start()function.
- Always start sessions 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><head>    <title>My Page</title></head>Adding Session Data
Section titled “Adding Session Data”The $_SESSION superglobal array is used to store data in a session.
- The key is the name of the data you want to store.
- The value is the data you want to store.
<?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['user_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, " . $_SESSION['username'];} else {    echo "Please log in";}
// Get data with default value (if 'theme' doesn't exist, use 'light')$theme = $_SESSION['theme'] ?? 'light';?>Removing Session Data
Section titled “Removing Session Data”Remove Specific Items
Section titled “Remove Specific Items”<?phpsession_start();
// Remove single itemunset($_SESSION['cart']);unset($_SESSION['temp_data']);?>Remove All Session Data
Section titled “Remove All Session Data”<?phpsession_start();
// Method 1: Clear all session variables$_SESSION = [];
// Method 2: Destroy the entire sessionsession_destroy();?>Common Session Functions
Section titled “Common Session Functions”There are several functions that can be used to work with sessions.
| Function | Purpose | 
|---|---|
| session_start() | Start or resume a session | 
| session_destroy() | Destroy all session data | 
| session_regenerate_id() | Generate new session ID | 
| session_unset() | Clear all session variables | 
| isset($_SESSION['key']) | Check if session variable exists | 
| unset($_SESSION['key']) | Remove specific session variable | 
Session Configuration
Section titled “Session Configuration”Setting Session Timeout
Section titled “Setting Session Timeout”An expiry time can be set for a session to prevent users from accessing their session data after a certain period of time.
You can set the session timeout by using the session.gc_maxlifetime and session.cookie_lifetime ini settings.
- session.gc_maxlifetimeis the maximum lifetime of a session in seconds.
- session.cookie_lifetimeis the lifetime of the session cookie in seconds.
The session cookie will be deleted when the browser is closed.
<?php// Set session timeout to 30 minutes (1800 seconds)ini_set('session.gc_maxlifetime', 1800); // 30 minutes in secondsini_set('session.cookie_lifetime', 0); // 0 = until browser closes
if (isset($_SESSION['last_activity'])) {    if (time() - $_SESSION['last_activity'] > $timeout) {        // Session expired        session_unset();        session_destroy();        header('Location: login.php');        exit;    }}
// Update last activity time$_SESSION['last_activity'] = time();?>Session Security Tips
Section titled “Session Security Tips”- 
Always regenerate session ID after login: session_regenerate_id(true);
- 
Set secure session settings in php.ini or code: ini_set('session.cookie_httponly', 1);ini_set('session.cookie_secure', 1);
- 
Implement session timeout: // Check if session has expired (30 minutes)if (time() - $_SESSION['last_activity'] > 1800) {session_unset();session_destroy();}$_SESSION['last_activity'] = time();
Quick Session Examples
Section titled “Quick Session Examples”Basic Usage
Section titled “Basic Usage”<?phpsession_start();
// Store data$_SESSION['username'] = 'john_doe';
// Read dataif (isset($_SESSION['username'])) {    echo "Hello, " . $_SESSION['username'];}
// Remove dataunset($_SESSION['username']);?>Shopping Cart
Section titled “Shopping Cart”<?phpsession_start();
// Initialize cartif (!isset($_SESSION['cart'])) {    $_SESSION['cart'] = [];}
// Add product$_SESSION['cart'][] = $product_id;
// Count items$item_count = count($_SESSION['cart']);?>