ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

PHP Tutorial• 7 min read

Sessions, Cookies & User State Management

Building secure login sessions and persistent client-side preferences

HTTP is a stateless protocol. To maintain user login state and shopping cart data across multiple page navigation events, PHP provides server-side sessions and client-side cookies.

Sessions vs Cookies

session_start(): Must be invoked at the very beginning of the script before sending any HTML output to initialize or restore the session.

$_SESSION: An associative array stored on the server tied to a unique cookie ID (PHPSESSID) held by the client.

setcookie(): Defines a small text cookie stored directly in the user browser with an expiration timestamp and domain flags.

Security essentials: Always flag cookies as HttpOnly (inaccessible to malicious JavaScript) and Secure (HTTPS only).

Session Authentication Workflow
<?php
  // Configure secure session cookie parameters
  session_start([
    'cookie_httponly' => true,
    'cookie_secure'   => true,
    'cookie_samesite' => 'Strict',
  ]);

  // Simulating user login
  function loginUser(int $userId, string $role): void {
    // Regenerate ID to prevent session fixation attacks
    session_regenerate_id(true);
    $_SESSION['user_id'] = $userId;
    $_SESSION['role'] = $role;
    $_SESSION['logged_in_at'] = time();
  }

  // Guarding a protected admin page
  if (empty($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    http_response_code(403);
    die("Access Denied: Administrative privileges required.");
  }

  echo "Welcome Admin User #" . $_SESSION['user_id'];
?>
session_regenerate_id(true) destroys the old session ID upon privilege elevation.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What is the purpose of the HttpOnly flag on session cookies?