Skip to content
Tutorials Center
My learning

Topics

Lesson 78 of 147 ยท PHP and the Web

Sessions

Learn how PHP sessions work: session_start, $_SESSION, session IDs and cookies, logging in and out safely, flash messages, locking and session security.

HTTP has no memory. Every request a browser sends is a brand-new conversation, and the server has no built-in way to know that the person asking for /cart is the same person who added a book to it a minute ago. Yet almost every real site needs to remember things between pages: who is logged in, what's in the shopping cart, which message to show after a form was saved.

Sessions are PHP's answer. The data stays on the server, and the browser only carries a long random session ID in a cookie. On each request PHP reads that ID, loads the matching data into the $_SESSION array, and saves it again when the script ends. You write ordinary array code; PHP does the bookkeeping.

This lesson shows how that works under the hood, how to store and remove data, how to log users in and out safely, how to build flash messages, and which settings keep sessions secure. It builds on Cookies, so read that first if cookies are new to you.

How a session works

Here's the life of a session across two requests. The first time a visitor arrives, they have no session cookie, so session_start() creates a new random ID and tells the browser to store it:

TEXT
GET /cart HTTP/1.1
Host: shop.example

HTTP/1.1 200 OK
Set-Cookie: PHPSESSID=4f9c1e7a0b2d48e6a3c5f7e9d1b3a5c7; path=/; HttpOnly; SameSite=Lax
Content-Type: text/html; charset=UTF-8

From then on, the browser sends the cookie back with every request to the site:

TEXT
GET /checkout HTTP/1.1
Host: shop.example
Cookie: PHPSESSID=4f9c1e7a0b2d48e6a3c5f7e9d1b3a5c7

On the server, the default "files" handler keeps each session in a small file named after its ID, such as /tmp/sess_4f9c1e7a0b2d48e6a3c5f7e9d1b3a5c7. In short:

  1. session_start() looks for the PHPSESSID cookie. If there is none, it generates a new ID and queues a Set-Cookie header.
  2. It reads the session file for that ID (and locks it), unserializes the data and puts it in $_SESSION.
  3. Your script reads and changes $_SESSION like any array.
  4. When the script ends (or you call session_write_close()), PHP serializes $_SESSION back into the file and releases the lock.

The browser never sees the data itself, only the ID. That's the big difference from cookies: a user can read and edit their cookies, but they can't edit $_SESSION. The flip side is that the ID is the key to the whole session. Anyone who gets hold of it can act as that user, which is why most of the security advice later in this lesson is about protecting the ID.

Starting a session

On a real web page, you call session_start() near the top of the script, before anything is printed:

PHP
<?php
declare(strict_types=1);

session_start();

$_SESSION['visits'] = ($_SESSION['visits'] ?? 0) + 1;
?>
<p>You have visited this page <?= $_SESSION['visits'] ?> time(s).</p>

Why before any output? Starting a session may send a Set-Cookie header, and HTTP headers must come before the body. Once PHP has sent even one byte of the page (an echo, a blank line before <?php, a UTF-8 byte order mark), it's too late, and you get warnings like this one:

TEXT
Warning: session_start(): Session cannot be started after headers have already been sent (sent from main.php on line 2) in main.php on line 4

The next lesson explains the "headers already sent" problem in depth.

Our editor runs PHP on the command line, where there's no browser to keep a cookie. Sessions still work there, though: PHP really creates the session file and really loads it again. To act out several page views, the demo below uses a small request() helper that does the browser's job, passing the ID from one "request" to the next with session_id(). It's a simulation of the cookie exchange, but the session machinery is the real one.

PHP A visit counter across simulated requests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first three requests share one ID, so the counter climbs to 3. The fourth "browser" sends no cookie, gets a new session and starts at 1. The ID is 32 hexadecimal characters of randomness, which is far too many to guess.

ob_start() at the top turns on output buffering: everything that's echoed is held back until the script ends, so PHP never considers the headers "sent" and can start sessions as often as the simulation needs. Real pages don't need this trick because they call session_start() once, before any output.

Checking whether a session is active

session_start() returns false if it fails, and calling it twice in one request triggers a notice. Library code that can't be sure whether the session has started checks session_status(), which returns one of three constants:

PHP
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
// PHP_SESSION_DISABLED: sessions are turned off on this server
// PHP_SESSION_NONE:     available but not started yet
// PHP_SESSION_ACTIVE:   already started

Storing, reading and removing data

$_SESSION is a normal associative array, so everything from Associative Arrays applies. You can store strings, numbers, booleans, null and nested arrays. Objects work too, but their class must be loaded before session_start() on later requests, so most apps keep sessions to plain arrays and IDs.

What should go in a session? Small things that belong to this visitor: the logged-in user's ID, a cart of product IDs and quantities, a CSRF token, a language choice. What should not: whole database rows that can go stale, large data, passwords (not even hashed ones), and resources like database connections, which can't be serialized at all.

PHP Storing a cart in the session

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last line prints the session in the format the default handler stores on disk: cart|a:1:{i:101;i:3;}. Each top-level key is followed by | and the value in PHP's serialize() format. You'll never need to write this by hand, but seeing it makes the mechanism less magical: a session really is just serialized data in a file, found by its ID.

Never call unset($_SESSION) to empty a session. It destroys the superglobal variable itself and stops PHP from saving changes. To clear everything, assign an empty array: $_SESSION = [];.

Session behavior is controlled by session.* settings in php.ini. These are the ones worth setting on every production server:

INI
session.use_strict_mode = 1      ; reject session IDs the server never created
session.use_only_cookies = 1     ; never accept IDs from the URL (?PHPSESSID=...)
session.cookie_httponly = 1      ; JavaScript can't read the session cookie
session.cookie_secure = 1        ; only send the cookie over HTTPS
session.cookie_samesite = "Lax"  ; don't send it on most cross-site requests
session.gc_maxlifetime = 1440    ; seconds before an unused session may be deleted

PHP's built-in defaults are more permissive: use_strict_mode, cookie_httponly and cookie_secure are all off, and cookie_samesite is empty. If you can't edit php.ini (shared hosting, say), pass the same options to session_start() with the session. prefix removed. They apply to that request only:

PHP
session_start([
    'use_strict_mode' => true,
    'cookie_httponly' => true,
    'cookie_secure' => true,
    'cookie_samesite' => 'Lax',
]);

You can also rename the cookie with session_name('app_session') (before session_start()). A neutral name hides the fact that the site runs PHP, which is a small bonus, and it keeps two apps on the same domain from overwriting each other's sessions.

PHP Default settings vs a hardened start

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

session_get_cookie_params() shows exactly which attributes the Set-Cookie header will carry. (The partitioned key is new in PHP 8.5; it controls the Partitioned cookie attribute used for embedded third-party content.) A lifetime of 0 means a "session cookie" in the browser sense: it disappears when the browser is closed. You can set a longer lifetime, but it's usually better to keep the cookie short-lived and build a separate, carefully designed "remember me" feature (covered in Project: Login System).

Session fixation and session_regenerate_id()

Imagine an attacker could make your browser use a session ID they chose, for example through a link with ?PHPSESSID=known-value on a server that accepts IDs from URLs. You log in, PHP stores your user ID in that session, and now the attacker, who knows the ID, is logged in as you. This is session fixation.

Two defenses stop it:

  • Strict mode (session.use_strict_mode = 1) makes PHP ignore any ID it didn't create itself and issue a fresh one instead.
  • Regenerate the ID whenever privileges change, above all right after a successful login. session_regenerate_id(true) gives the current session a new ID, keeps the data, and (because of true) deletes the old session file so the old ID becomes useless.
PHP Strict mode and regenerating the ID

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

session_save_path() returns an empty string when no folder is configured, and then PHP uses the system temporary folder, which is why the demo falls back to sys_get_temp_dir(). The old file exists until session_regenerate_id(true) deletes it. With false (the default), the old session would stay on disk and its ID would keep working until garbage collection removed it.

Session fixation is one way to steal a session; session hijacking (stealing an existing ID) is the other. HTTPS everywhere, HttpOnly cookies and good XSS protection keep the ID from leaking. Don't bind sessions tightly to the IP address: mobile users change IPs constantly.

Logging in and logging out

A login handler checks the password, regenerates the ID, and stores the user's ID, not the whole user record. Every later request uses that ID to load fresh data from the database, so role changes and bans take effect immediately:

PHP
<?php
declare(strict_types=1);

session_start();

$user = findUserByEmail($_POST['email'] ?? '');   // your database lookup

if ($user !== null && password_verify($_POST['password'] ?? '', $user['password_hash'])) {
    session_regenerate_id(true);                   // new ID for the new privilege level
    $_SESSION['user_id'] = $user['id'];
    header('Location: /dashboard', true, 303);
    exit;
}

Password checking with password_verify() is explained in Password Hashing. Logging out properly takes three steps: empty the data, expire the cookie, and destroy the stored session:

PHP
<?php
session_start();

$_SESSION = [];                                    // 1. forget the data

$params = session_get_cookie_params();             // 2. expire the cookie
setcookie(session_name(), '', [
    'expires' => time() - 3600,
    'path' => $params['path'],
    'domain' => $params['domain'],
    'secure' => $params['secure'],
    'httponly' => $params['httponly'],
    'samesite' => $params['samesite'],
]);

session_destroy();                                 // 3. delete the server-side session

header('Location: /', true, 303);
exit;

session_destroy() alone isn't enough: it deletes the stored data, but $_SESSION still holds values for the rest of the script, and the browser keeps sending the old ID. The cookie must be expired with the same path and domain it was set with, which is why the code reads them from session_get_cookie_params().

Here's the full flow acted out with the simulated browser from earlier. Each page is a closure, and the "browser" keeps whatever ID the last response gave it:

PHP Login, protected page and logout

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

After logout the browser still sends the old ID (the simulation doesn't expire cookies), but the session behind it is gone, and strict mode refuses to revive it. The dashboard treats the visitor as a guest again.

session_unset() versus session_destroy()

These two functions sound alike and are constantly confused, so be precise about what each one does:

session_unset() session_destroy()
Clears the data in $_SESSION Yes, empties the array No, the array keeps its values for the rest of the script
Deletes the session's stored data (the file or database row) No, it stays but is empty after the next write Yes, the storage is removed
Ends the active session No, the session stays open Yes, the session becomes inactive
Removes the browser's cookie No No
Typical use Reset the data but keep the session, e.g. "clear my wizard" Part of logging out

unset($_SESSION['key']) removes one entry, and $_SESSION = [] is the idiomatic way to empty the array. session_unset() does the same job as $_SESSION = [] while a session is active; modern code usually writes the assignment because it is more obvious.

The practical rule: neither function alone is a logout. A complete logout (shown earlier in Logging in and logging out) needs three steps, in this order: empty the array, expire the cookie, destroy the storage. The cookie step matters because session_destroy() never touches the browser's copy of the ID.

PHP What unset and destroy really do

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Look at the last line: after session_destroy() the session is inactive and the file is gone, yet $_SESSION still holds {"again":1}. That is why the logout recipe assigns $_SESSION = [] first; otherwise the rest of the request could still read data from a session that has just been "destroyed".

A reusable logout function

Putting the three steps in one function prevents the classic mistake of forgetting one of them. Call it from a POST handler protected by a CSRF token, never from a link that anyone can trigger by embedding an image:

PHP
function logout(): void
{
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }

    $_SESSION = [];                                          // 1. data

    if (ini_get('session.use_cookies')) {                     // 2. browser cookie
        $p = session_get_cookie_params();
        setcookie(session_name(), '', [
            'expires'  => time() - 42000,
            'path'     => $p['path'],
            'domain'   => $p['domain'],
            'secure'   => $p['secure'],
            'httponly' => $p['httponly'],
            'samesite' => $p['samesite'],
        ]);
    }

    session_destroy();                                       // 3. server storage
}

Two more points. If you only want to end a login but keep other data such as a language choice or a cart, unset($_SESSION['user_id']) plus session_regenerate_id(true) is enough: the visitor stays on the same session without the privilege. And to log a user out of all devices you need to delete every session stored for that user, which means keeping sessions in a database or Redis under your control (see Locking, timeouts and storage).

Flash messages

A flash message is a one-time note that survives exactly one redirect: "Your profile was saved." The handler stores it in the session, redirects (see Handling Forms for the POST-redirect-GET pattern), and the next page shows it and deletes it so a reload doesn't show it again.

PHP Flash messages that show once

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is HTML source, printed as text here; in a browser it would render as two paragraphs. Note the htmlspecialchars() calls: a flash message often contains user input (a name, a file name), so it must be escaped like any other output.

Locking, timeouts and storage

Session locking

The files handler locks a session file from session_start() until the script finishes. If a page fires five AJAX requests at once with the same session, they run one after another, not in parallel. When a script only needs to read the session, release the lock early:

PHP
session_start();
$userId = $_SESSION['user_id'] ?? null;
session_write_close();          // save and unlock; later changes are not saved

// ... slow work (reports, API calls) without blocking the user's other requests

// Or, for read-only access, open and close in one step:
session_start(['read_and_close' => true]);

Expiry and idle timeouts

session.gc_maxlifetime says how many seconds an unused session must sit before PHP's garbage collector may delete it. "May" is the key word: cleanup runs randomly (controlled by session.gc_probability and session.gc_divisor), so it's not a reliable logout timer. For a real idle timeout, store a timestamp and check it yourself:

PHP
session_start();

$idleLimit = 30 * 60;   // 30 minutes
if (isset($_SESSION['last_seen']) && time() - $_SESSION['last_seen'] > $idleLimit) {
    $_SESSION = [];
    session_regenerate_id(true);
}
$_SESSION['last_seen'] = time();

Storing sessions elsewhere

Files in a temporary folder work for one server. Once a site runs on several servers behind a load balancer, every server needs to see the same sessions, so they move to a shared store such as Redis (with the redis extension) or a database. With Redis it's a two-line change in php.ini:

INI
session.save_handler = redis
session.save_path = "tcp://127.0.0.1:6379"

For full control you can write your own handler class implementing SessionHandlerInterface and register it with session_set_save_handler(). Frameworks do exactly this to offer database, cache and cookie-based session drivers.

Security checklist: HTTPS only, use_strict_mode, HttpOnly, Secure and SameSite cookies, session_regenerate_id(true) after login, store IDs rather than whole records, implement idle timeouts yourself, and log out by clearing data, expiring the cookie and destroying the session. Sessions also hold the token that blocks CSRF attacks.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where is the data in $_SESSION stored with PHP's default configuration?

    The default "files" handler keeps each session in a file such as sess_<id> on the server. The browser only holds the ID in a cookie.
  2. 2. A page prints its HTML header and then calls session_start(). What happens?

    Starting a session may need to send a Set-Cookie header, and headers can't be sent after output. PHP emits a warning and the session doesn't start.
  3. 3. Why should you call session_regenerate_id(true) right after a successful login?

    Regenerating gives the session a new ID and deletes the old one, which defeats session fixation. The session data is kept.
  4. 4. Which logout code is complete?

    You need to clear the data in memory, tell the browser to forget the cookie, and delete the stored session. unset($_SESSION) breaks session saving instead.
  5. 5. A page fires several AJAX requests at once using the same session, and they finish one by one. What's the likely cause and fix?

    The files handler locks the session from session_start() until the script ends. Closing the session early (or using read_and_close) lets the other requests proceed.

Summary

  • HTTP is stateless. A session keeps per-visitor data on the server and gives the browser only a random session ID in a cookie (PHPSESSID by default).
  • Call session_start() before any output, then read and write $_SESSION like an array. Use ?? default for keys that might not exist and unset($_SESSION['key']) to remove one.
  • Store small, serializable data: user IDs, carts, tokens. Never store passwords or resources, and never unset($_SESSION) itself.
  • Harden sessions with use_strict_mode, use_only_cookies, HttpOnly, Secure and SameSite cookies, either in php.ini or as session_start() options.
  • Call session_regenerate_id(true) after login to defeat session fixation. Log out by clearing $_SESSION, expiring the cookie and calling session_destroy().
  • Flash messages are stored, shown once and deleted. Release the session lock early with session_write_close(), build idle timeouts yourself, and move sessions to Redis or a database when you have more than one server.

Next: HTTP Headers, Status Codes and Redirects