SyntaxStudy
Sign Up
PHP Beginner 6 min read

Session Basics

Sessions allow you to persist data across multiple HTTP requests for a single user. PHP stores session data on the server and sends a session ID to the browser via a cookie (PHPSESSID by default).

  • Call session_start() at the very beginning of every page that uses sessions — before any output.
  • Store and read data via the $_SESSION superglobal array.
  • Use session_destroy() to end a session (e.g., on logout).
Example
<?php
// Must be called before any output
session_start();

// Store data
$_SESSION['user_id']   = 42;
$_SESSION['username']  = 'alice';
$_SESSION['logged_in'] = true;

// Read data on another page (after session_start())
$userId   = $_SESSION['user_id']   ?? null;
$username = $_SESSION['username']  ?? 'Guest';

if ($_SESSION['logged_in'] ?? false) {
    echo "Welcome back, $username!";
} else {
    echo 'Please log in.';
}

// Remove a single key
unset($_SESSION['temp_value']);

// Destroy the entire session (logout)
session_start();
$_SESSION = [];                   // Clear array
session_destroy();                // Destroy server-side data

// Also delete the cookie
if (ini_get('session.use_cookies')) {
    $p = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $p['path'], $p['domain'], $p['secure'], $p['httponly']);
}
Pro Tip

Tip: Always call session_start() before sending any output (HTML, whitespace, or even a BOM). Consider using output buffering (ob_start()) or move your session logic into a front controller to guarantee this ordering.