W3docs

PHP Sessions: A Comprehensive Guide

Learn how PHP sessions work, how to store and retrieve session data, and how to secure sessions against fixation and hijacking attacks.

HTTP is stateless — each request a browser makes is independent, and the server forgets everything once it sends a response. Sessions are how PHP remembers a visitor between requests: they let you keep a user logged in, build a shopping cart, or remember preferences as the user moves from page to page. This guide covers what sessions are, how they work under the hood, how to read and write session data, and how to keep them secure.

What are PHP Sessions?

A PHP session is a mechanism for storing per-user data on the server side for the duration of a user's visit. Unlike cookies, which store data in the browser, a session keeps the actual data on the server and only sends the browser a small session ID to identify which data belongs to whom.

This matters for two reasons:

  • Capacity — cookies are limited to about 4 KB and live in the browser; session data lives in server storage (files, a database, or memory) and can be much larger.
  • Security — sensitive values (a user's ID, role, or cart contents) never leave the server, so the browser cannot read or tamper with them. Only the opaque session ID is exposed.

How do PHP Sessions Work?

When a session starts, PHP generates a unique session ID for the visitor and sends it to the browser in a cookie named PHPSESSID. On every later request the browser returns that cookie, and PHP uses the ID to look up the matching data stored on the server. The data itself is exposed to your code as the $_SESSION array.

Session Workflow

graph LR
A[Browser] -- 1. Request + Session Cookie --> B[Server]
B -- 2. Validate Cookie & Fetch Data --> A
A -- 3. Receive Response --> B

In short: the cookie carries the ID; the server holds the data.

Starting a Session

Every page that reads or writes session data must call session_start() before any output is sent to the browser. Because session_start() sends the PHPSESSID cookie via an HTTP header, even a single space or blank line before the opening <?php tag will trigger a "headers already sent" warning and break the session.

Calling session_start() either resumes the visitor's existing session (if their browser sent a valid ID) or starts a fresh one. Guarding the call with session_status() avoids a notice if the session was already started earlier in the request:

How to start a PHP session

<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

Reading and Writing Session Data

Once a session is started, the $_SESSION superglobal behaves like any other associative array. Assign to a key to store a value:

Store data in a PHP session

<?php
$_SESSION['username'] = 'John Doe';
$_SESSION['cart'] = ['book', 'pen'];

Read it back on the same page or on any later request in the same session:

Retrieve data from a PHP session

<?php
// Always check the key exists to avoid a warning
$username = $_SESSION['username'] ?? 'Guest';

echo "Welcome, {$username}";

Because the data persists across requests, a common pattern is a page-view counter that survives reloads:

Count page views in the current session

<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$_SESSION['views'] = ($_SESSION['views'] ?? 0) + 1;

echo "You have viewed this page {$_SESSION['views']} time(s).";

To remove a single value, use unset() on its key — do not assign null, which leaves the key in place:

<?php
unset($_SESSION['cart']);

Sessions vs. Cookies

Sessions and cookies often work together, but they store data in different places. Reach for a session when the data is sensitive or large; reach for a cookie when the browser itself needs to remember something (like a "remember me" token) across visits.

SessionCookie
Stored onServerBrowser
Visible to userNo (only the ID)Yes
Size limitLarge (server storage)~4 KB
LifetimeUntil browser closes or timeoutConfigurable expiry

Securing PHP Sessions

It's important to secure PHP sessions to prevent unauthorized access to sensitive user data. You can secure your PHP sessions in several ways:

  • Regenerate the session ID periodically.
  • Store the session data on the server-side in a secure directory.
  • Use HTTPS to protect the transmission of session data.

Regenerate the session ID and harden the cookie

The hardening options must be set before session_start(), otherwise the cookie has already been sent with the old settings. Regenerating the ID right after a privilege change (such as a login) defeats session fixation attacks, where an attacker tricks a victim into using a session ID the attacker already knows:

<?php
// Configure before the session starts
ini_set('session.cookie_secure', '1');   // send cookie over HTTPS only
ini_set('session.use_only_cookies', '1'); // never accept the ID from the URL
ini_set('session.cookie_httponly', '1');  // hide the cookie from JavaScript

session_start();

// After a successful login, swap the ID and discard the old one
session_regenerate_id(true);
SettingWhat it prevents
cookie_secureSession ID leaking over plain HTTP
cookie_httponlyJavaScript (XSS) stealing the cookie
use_only_cookiesSession IDs being passed in URLs
session_regenerate_idSession fixation after a login

Ending a PHP Session

To log a user out, clear the data and destroy the session. Emptying $_SESSION removes the variables; session_destroy() discards the data on the server; and deleting the cookie stops the browser from sending the stale ID:

<?php
session_start();

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

// 2. Delete the session cookie in 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']);
}

// 3. Destroy the data stored on the server
session_destroy();

Conclusion

In conclusion, PHP sessions are an essential tool for storing user data on the server-side and improving the user experience on your website. By understanding how they work and how to use them, you can take full advantage of the benefits they offer. With proper security measures in place, you can also ensure that sensitive user data is protected.

Practice

Practice
What can be accomplished using PHP sessions?
What can be accomplished using PHP sessions?
Was this page helpful?