PHP Session Management: Complete Guide to Sessions and Cookies (2026)

By Lyndon Bermoy

Updated on:

PHP Session Management: Complete Guide to Sessions and Cookies (2026)

HTTP is stateless — every request is independent and the server has no memory of previous requests. Sessions and cookies solve this: they give PHP applications a way to remember who a user is across multiple page loads and requests. This guide covers the complete session and cookie lifecycle with security best practices.

Sessions vs Cookies

Feature Sessions Cookies
Storage location Server (files/database/Redis) Client browser
Size limit Effectively unlimited 4KB per cookie
Security Better — data on server Weaker — data on client
Expiry Browser close or server-side timeout Explicit expiry date
Use case Login state, shopping cart, user preferences Persistent preferences, tracking

Basic Session Usage

<?php
// Must be called before any output (including whitespace):
session_start();

// Store data in session:
$_SESSION['user_id']   = 42;
$_SESSION['user_name'] = 'Lyndon';
$_SESSION['role']      = 'admin';

// Read session data:
if (isset($_SESSION['user_id'])) {
    echo "Welcome back, {$_SESSION['user_name']}!";
}

// Delete a specific session variable:
unset($_SESSION['role']);

// Destroy the entire session (logout):
session_unset();    // Clear all session variables
session_destroy();  // Destroy session data on server

Secure Session Configuration

// Set these BEFORE session_start():
ini_set('session.use_strict_mode',   '1');  // Reject uninitialized session IDs
ini_set('session.cookie_httponly',   '1');  // Inaccessible to JavaScript
ini_set('session.cookie_secure',     '1');  // HTTPS only
ini_set('session.cookie_samesite',   'Strict'); // Prevent CSRF via cookie
ini_set('session.gc_maxlifetime',    '1800'); // 30 min idle timeout
ini_set('session.cookie_lifetime',   '0');  // Session cookie expires on browser close
ini_set('session.use_only_cookies',  '1');  // No session IDs in URLs

session_start();

Session Fixation Prevention

// After successful login, ALWAYS regenerate the session ID:
function login(int $user_id, string $user_name): void {
    // Regenerate session ID and delete old session data:
    session_regenerate_id(true);

    $_SESSION['user_id']        = $user_id;
    $_SESSION['user_name']      = $user_name;
    $_SESSION['logged_in']      = true;
    $_SESSION['login_time']     = time();
    $_SESSION['last_activity']  = time();
    $_SESSION['ip_address']     = $_SERVER['REMOTE_ADDR'];
    $_SESSION['user_agent']     = $_SERVER['HTTP_USER_AGENT'] ?? '';
}

Session Timeout

function check_session_timeout(int $timeout_seconds = 1800): bool {
    if (!isset($_SESSION['last_activity'])) {
        return false; // No active session
    }

    if (time() - $_SESSION['last_activity'] > $timeout_seconds) {
        // Session expired:
        session_unset();
        session_destroy();
        header('Location: /login?reason=timeout');
        exit;
    }

    // Update activity timestamp:
    $_SESSION['last_activity'] = time();
    return true;
}

// Call at the top of every protected page:
session_start();
check_session_timeout();

Session Hijacking Prevention

// Bind session to IP and user agent (prevents token theft across devices):
function validate_session_fingerprint(): bool {
    $current_ip = $_SERVER['REMOTE_ADDR'];
    $current_ua = $_SERVER['HTTP_USER_AGENT'] ?? '';

    if (!isset($_SESSION['ip_address']) || !isset($_SESSION['user_agent'])) {
        return false;
    }

    // Strict IP check (can be relaxed for mobile users on changing IPs):
    if ($_SESSION['ip_address'] !== $current_ip) {
        session_unset();
        session_destroy();
        return false;
    }

    if ($_SESSION['user_agent'] !== $current_ua) {
        session_unset();
        session_destroy();
        return false;
    }

    return true;
}

Working with Cookies

// Set a cookie (call BEFORE any output):
setcookie(
    'user_preference',        // Name
    'dark_mode',              // Value
    [
        'expires'  => time() + (86400 * 30), // 30 days
        'path'     => '/',                    // Available site-wide
        'domain'   => 'campcodes.com',
        'secure'   => true,                   // HTTPS only
        'httponly' => true,                   // No JavaScript access
        'samesite' => 'Lax',                  // CSRF protection
    ]
);

// Read a cookie:
$preference = $_COOKIE['user_preference'] ?? 'light_mode';

// Delete a cookie (set expiry in the past):
setcookie('user_preference', '', [
    'expires'  => time() - 3600,
    'path'     => '/',
    'secure'   => true,
    'httponly' => true,
]);

Remember Me Functionality

// Generate a secure "remember me" token:
function set_remember_me_cookie(int $user_id, PDO $db): void {
    $token    = bin2hex(random_bytes(32));
    $selector = bin2hex(random_bytes(8));
    $hash     = hash('sha256', $token);

    // Store hashed token in database:
    $stmt = $db->prepare(
        "INSERT INTO remember_tokens (user_id, selector, token_hash, expires_at)
         VALUES (?, ?, ?, ?)"
    );
    $stmt->execute([$user_id, $selector, $hash, date('Y-m-d H:i:s', time() + 86400 * 30)]);

    // Set cookie with selector:token format:
    setcookie('remember_token', "$selector:$token", [
        'expires'  => time() + 86400 * 30,
        'path'     => '/',
        'secure'   => true,
        'httponly' => true,
        'samesite' => 'Strict',
    ]);
}

// Verify remember me cookie:
function verify_remember_me(PDO $db): ?int {
    if (!isset($_COOKIE['remember_token'])) return null;

    [$selector, $token] = explode(':', $_COOKIE['remember_token'], 2);
    $hash  = hash('sha256', $token);

    $stmt = $db->prepare(
        "SELECT user_id FROM remember_tokens
         WHERE selector = ? AND token_hash = ? AND expires_at > NOW()"
    );
    $stmt->execute([$selector, $hash]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    return $row ? (int)$row['user_id'] : null;
}

Session Storage Backends

By default, PHP stores sessions in server files (/tmp or a configured directory). For production applications, consider:

  • Redis — fast, shared across multiple servers (required for load-balanced deployments). Set session.save_handler = redis and session.save_path = "tcp://127.0.0.1:6379"
  • Database — sessions in MySQL, queryable, easy to implement admin “view active sessions” features
  • Memcached — similar to Redis for multi-server setups
READ ALSO:   How to Create Login and Logout Page with Session and Cookies in PHP

Frequently Asked Questions

What is the difference between session_unset() and session_destroy()?

session_unset() clears all variables from the current session (equivalent to $_SESSION = []) but keeps the session alive on the server. session_destroy() deletes the session data from the server. For proper logout: call session_unset(), then session_destroy(), then also delete the session cookie.

How long do sessions last?

By default, until the browser closes (if session.cookie_lifetime = 0) or until the server’s garbage collection runs after session.gc_maxlifetime seconds of inactivity (default 1440 seconds = 24 minutes). Set session.gc_maxlifetime = 1800 for 30-minute sessions.

Conclusion

PHP sessions and cookies are straightforward to use but require careful security configuration. The key hardening steps: set httponly and secure on cookies, call session_regenerate_id(true) after login, implement activity-based timeout, and use HTTPS for all session cookie transmission. With these in place, your session management is production-ready.

Next Step for Your Project Journey

Pick your next action to keep building: download complete source code, continue with practical tutorials, or explore more project systems.

Explore Source Code Continue Tutorials Final Year Projects

Leave a Comment