Skip to content

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

  1. Server creates a unique session ID
  2. Session ID sent to browser as a cookie
  3. Browser sends session ID with each request
  4. Server uses session ID to retrieve stored data

  • 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:
<?php
session_start(); // Must be first thing in your PHP file
?>
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>

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.
Adding Session Data
<?php
session_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'
];
?>

Always check if data exists before using it:

<?php
session_start();
// Check if session data exists
if (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';
?>

<?php
session_start();
// Remove single item
unset($_SESSION['cart']);
unset($_SESSION['temp_data']);
?>
<?php
session_start();
// Method 1: Clear all session variables
$_SESSION = [];
// Method 2: Destroy the entire session
session_destroy();
?>

There are several functions that can be used to work with sessions.

FunctionPurpose
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

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_maxlifetime is the maximum lifetime of a session in seconds.
  • session.cookie_lifetime is the lifetime of the session cookie in seconds.

The session cookie will be deleted when the browser is closed.

Setting Session Timeout
<?php
// Set session timeout to 30 minutes (1800 seconds)
ini_set('session.gc_maxlifetime', 1800); // 30 minutes in seconds
ini_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();
?>

  1. Always regenerate session ID after login:

    session_regenerate_id(true);
  2. Set secure session settings in php.ini or code:

    ini_set('session.cookie_httponly', 1);
    ini_set('session.cookie_secure', 1);
  3. Implement session timeout:

    // Check if session has expired (30 minutes)
    if (time() - $_SESSION['last_activity'] > 1800) {
    session_unset();
    session_destroy();
    }
    $_SESSION['last_activity'] = time();

<?php
session_start();
// Store data
$_SESSION['username'] = 'john_doe';
// Read data
if (isset($_SESSION['username'])) {
echo "Hello, " . $_SESSION['username'];
}
// Remove data
unset($_SESSION['username']);
?>
<?php
session_start();
// Initialize cart
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
// Add product
$_SESSION['cart'][] = $product_id;
// Count items
$item_count = count($_SESSION['cart']);
?>