Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Variables and Constants

PHP $_SESSION superglobal

Reference for PHP $_SESSION: start a session, store and read values per visitor, log in and out safely, and avoid common session mistakes.

$_SESSION is an array whose contents persist between requests of the same visitor. PHP stores the data on the server (by default in files) and gives the browser only a random session ID in a cookie, usually named PHPSESSID. On each request the ID is used to load the stored array back into $_SESSION.

The array does not exist until you call session_start(). Call it before any output is sent, because it needs to send a cookie header. Anything you put into $_SESSION is written back when the script ends, or when you call session_write_close().

PHP
<?php
session_start();
$_SESSION["visits"] = ($_SESSION["visits"] ?? 0) + 1;

Try it

These examples run in a command-line script, so there is no browser and no cookie. The session still works inside one run, which is enough to show how $_SESSION behaves. We keep the session files in a temporary folder.

PHP Starting a session and storing values

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.

PHP Logging out and flash messages

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.

In a web request the typical login and logout code looks like this (read-only, it needs a browser):

PHP
<?php
session_start();

// After the password was verified:
session_regenerate_id(true);   // new ID, old one deleted: stops session fixation
$_SESSION["user_id"] = $user["id"];

// On logout:
$_SESSION = [];
$params = session_get_cookie_params();
setcookie(session_name(), "", time() - 3600, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
session_destroy();

Syntax

PHP
session_start(array $options = []): bool
$_SESSION["key"] = $value;
Part Description
session_start() Starts or resumes the session and fills $_SESSION. Returns false on failure. Options such as ["cookie_httponly" => true] override ini settings for this call.
$_SESSION Array of your data. Use descriptive string keys; values must be serializable (no resources, no closures).
session_id() The current ID (empty before the session starts).
session_regenerate_id(bool $delete_old_session = false) Issues a new ID for the same data.
session_destroy() Deletes the stored data. It does not unset $_SESSION in the running script, so empty the array yourself.
session_write_close() Saves and closes the session early to release the file lock.

Errors: calling session_start() after output was sent raises a warning ("Session cannot be started after headers have already been sent") and returns false.

Usage notes

  • Start before output. Even a space or a byte-order mark before <?php breaks it. In a script that includes other files, call session_start() at the very top.
  • Check the status with session_status(): PHP_SESSION_NONE, PHP_SESSION_ACTIVE or PHP_SESSION_DISABLED. Starting a session twice gives a notice.
  • Regenerate the ID at login (session_regenerate_id(true)) and again when privileges change. This blocks session fixation.
  • Cookie flags. Use session.cookie_httponly=1, session.cookie_secure=1 on HTTPS, session.cookie_samesite=Lax (or Strict), and session.use_strict_mode=1 so PHP rejects IDs it did not create.
  • Store IDs, not objects. Keep small values such as a user ID and load the record from the database. Objects need their class defined (or an autoloader) before session_start(), and secrets in sessions end up in plain files.
  • File locking. With the default file handler, a second request from the same visitor waits until the first closes its session. Call session_write_close() as soon as you are done writing, for example before a long download.
  • Lifetime. session.gc_maxlifetime controls when old data may be deleted, not when the browser forgets the cookie. A cookie lifetime of 0 means "until the browser closes".
  • Not shared between users or servers. Behind several servers, use a shared handler (Redis, database) or sticky sessions.
  • Destroying. session_destroy() leaves $_SESSION filled until the script ends. Set $_SESSION = [] first.
  • Caches. Pages that read $_SESSION should not be publicly cached. PHP sends no-cache headers for them by default (session.cache_limiter).
  • CSRF and sessions are linked: store a per-session token in $_SESSION and compare it with the one in the form. See CSRF protection.