PHP Sessions

A session is a way to store information about a user across multiple page requests. HTTP, the protocol used by websites, is stateless — each page request is independent and has no memory of previous requests. Sessions solve this problem by maintaining user-specific data on the server for the duration of a visit. This is how websites remember that a user is logged in as they navigate from page to page.

How Sessions Work

When a session starts, PHP generates a unique session ID and stores it as a cookie in the user's browser. On every subsequent request, the browser sends this ID back to the server. PHP uses the ID to locate the correct session data stored on the server. The user's browser only holds the ID — the actual data stays on the server.

Starting a Session

A session must be started at the very beginning of a PHP script, before any HTML output, using session_start().

<?php
  session_start();   // Must be called before anything is sent to the browser
?>
<!DOCTYPE html>
<html>
<body>
  <p>Session started.</p>
</body>
</html>

Calling session_start() either begins a new session or resumes an existing one based on the session cookie sent by the browser.

Storing Session Variables

Session data is stored in the $_SESSION superglobal array. Any value assigned to it persists across page requests for the same user.

<?php
  // login.php
  session_start();

  // Simulate a successful login
  $_SESSION['user_id'] = 101;
  $_SESSION['username'] = "alice";
  $_SESSION['role'] = "admin";

  echo "Login successful. Welcome, " . $_SESSION['username'] . "!";
?>

Reading Session Variables

<?php
  // dashboard.php
  session_start();

  if (isset($_SESSION['username'])) {
    echo "Hello, " . htmlspecialchars($_SESSION['username']) . "!";
    echo "Your role is: " . $_SESSION['role'];
  } else {
    echo "You are not logged in.";
    header("Location: login.php");
    exit;
  }
?>

Notice the use of isset() before accessing session variables. If the session variable was never set (or if the session expired), accessing it directly would produce a notice.

Modifying Session Variables

<?php
  session_start();

  // Initialize a page view counter
  if (!isset($_SESSION['page_views'])) {
    $_SESSION['page_views'] = 0;
  }

  $_SESSION['page_views']++;
  echo "You have visited this page " . $_SESSION['page_views'] . " time(s).";
?>

Each time this page loads, the counter increments and the new value is stored in the session — persisting until the session ends.

Removing Session Variables

A specific session variable can be removed with unset().

<?php
  session_start();

  $_SESSION['temp_message'] = "Welcome back!";
  echo $_SESSION['temp_message'];   // Outputs: Welcome back!

  unset($_SESSION['temp_message']);

  // Now the variable is gone
  echo isset($_SESSION['temp_message']) ? "Exists" : "Removed";   // Outputs: Removed
?>

Destroying a Session

When a user logs out, the session should be completely cleared and destroyed.

<?php
  // logout.php
  session_start();

  // Clear all session variables
  $_SESSION = [];

  // Delete the session cookie from the browser
  if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(
      session_name(), "", time() - 42000,
      $params["path"], $params["domain"],
      $params["secure"], $params["httponly"]
    );
  }

  // Destroy the session on the server
  session_destroy();

  echo "You have been logged out.";
  header("Location: login.php");
  exit;
?>

Session Security Best Practices

Regenerate Session ID After Login

After a successful login, always regenerate the session ID to prevent session fixation attacks.

<?php
  session_start();

  // After verifying username and password:
  session_regenerate_id(true);   // Creates new ID, deletes old session

  $_SESSION['user_id'] = 101;
  $_SESSION['username'] = "alice";
?>

Validate User Identity

<?php
  session_start();

  // Store user agent on login
  if (!isset($_SESSION['user_agent'])) {
    $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
  }

  // Validate on each request
  if ($_SESSION['user_agent'] !== $_SERVER['HTTP_USER_AGENT']) {
    session_destroy();
    header("Location: login.php");
    exit;
  }
?>

Session Configuration

<?php
  // Set session lifetime to 30 minutes
  ini_set("session.gc_maxlifetime", 1800);

  // Ensure cookies are only sent over HTTPS
  ini_set("session.cookie_secure", 1);

  // Prevent JavaScript from accessing the session cookie
  ini_set("session.cookie_httponly", 1);

  session_start();
?>

Key Points

  • session_start() must be called before any output on every page that uses sessions.
  • Session data is stored in $_SESSION and persists across page requests for the same user.
  • Session data lives on the server; only the session ID is stored in the user's browser cookie.
  • Use isset() before reading session variables to avoid undefined index notices.
  • unset($_SESSION['key']) removes a specific variable; session_destroy() ends the entire session.
  • Call session_regenerate_id(true) after a successful login to prevent session fixation.
  • Configure session security options (cookie_secure, cookie_httponly) for production environments.

Leave a Comment

Your email address will not be published. Required fields are marked *