Skip to content

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

  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

Call session_start() 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>
...

Use the $_SESSION superglobal array to store 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['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, " . htmlspecialchars($_SESSION['username']);
} else {
echo "Please log in";
}
// Get data with default value
$theme = $_SESSION['theme'] ?? 'light';
?>

<?php
session_start();
unset($_SESSION['cart']);
unset($_SESSION['temp_data']);
?>
<?php
session_start();
// Clear all session variables
$_SESSION = [];
// Delete the session cookie
if (ini_get('session.use_cookies')) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 3600, $params['path']);
}
// Destroy the session
session_destroy();
// Redirect to login page
header('Location: login.php');
exit;
?>

Flash messages are notifications that display once and then disappear. Useful for showing success/error messages after a redirect.

add_item.php
// Page 1: Set the flash message before redirecting
$_SESSION['flash'] = 'Item added to cart!';
header('Location: cart.php');
exit;
cart.php
// Page 2: Display and remove the message
session_start();
if (isset($_SESSION['flash'])) {
echo '<div class="alert">' . htmlspecialchars($_SESSION['flash']) . '</div>';
unset($_SESSION['flash']); // Remove so it only shows once
}

FunctionPurpose
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

Set an expiry time to automatically log out inactive users:

<?php
session_start();
$timeout = 1800; // 30 minutes in seconds
// Check if session has expired
if (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();
?>

  1. Regenerate session ID after login to prevent session fixation:

    session_regenerate_id(true);
  2. Use secure cookie settings:

    ini_set('session.cookie_httponly', 1); // Prevent JavaScript access
    ini_set('session.cookie_secure', 1); // HTTPS only
  3. Always use HTTPS when handling sessions with sensitive data.


<?php
session_start();
// Initialize cart if it doesn't exist
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
// Add product to cart
function addToCart($product_id) {
$_SESSION['cart'][] = $product_id;
}
// Remove product from cart
function removeFromCart($product_id) {
$key = array_search($product_id, $_SESSION['cart']);
if ($key !== false) {
unset($_SESSION['cart'][$key]);
}
}
// Get cart count
function getCartCount() {
return count($_SESSION['cart']);
}
?>