Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Web and Security

PHP sessions: session_start() and friends

Reference for PHP sessions: session_start() options, $_SESSION, session_regenerate_id(), session_destroy(), cookie settings, locking and secure login/logout patterns.

A session lets a site remember a visitor between requests. PHP stores the data on the server (by default in a file) and gives the browser only a random session ID in a cookie named PHPSESSID. On each request session_start() reads that cookie, loads the matching data into the $_SESSION array and, when the script ends, writes any changes back.

Sessions are the standard place for a logged-in user's ID, a shopping cart, flash messages and CSRF tokens. The data stays on your server; only the ID travels, so protect the ID well.

PHP
session_start();
$_SESSION['user_id'] = 42;
echo $_SESSION['user_id'];

Try it

Sessions normally start inside a web request, and session_start() sends a cookie header, which must happen before output. In the command-line editor the examples below use output buffering to allow that, point the session files at the temp folder and set the ID by hand to simulate two separate requests. In your own web code you need none of those extras: just session_start() at the top.

PHP Writing, reloading, regenerating and destroying

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 Strict mode, flash messages and a login check

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.

Syntax

PHP
session_start(array $options = []): bool
session_status(): int
session_id(?string $id = null): string|false
session_regenerate_id(bool $delete_old_session = false): bool
session_write_close(): bool
session_unset(): bool
session_destroy(): bool
session_set_cookie_params(array $options): bool
Function Description
session_start() Starts or resumes a session and fills $_SESSION. Options override session.* settings, for example cookie_lifetime, cookie_secure, cookie_httponly, cookie_samesite, use_strict_mode, read_and_close.
session_status() PHP_SESSION_DISABLED (0), PHP_SESSION_NONE (1) or PHP_SESSION_ACTIVE (2).
session_id() Reads or sets the current ID. Set it only before session_start().
session_regenerate_id(true) Issues a new ID and deletes the old file. Call it after login and privilege changes.
session_write_close() Saves the data and releases the lock early.
session_unset() Empties $_SESSION (the stored data is rewritten at the end).
session_destroy() Deletes the stored session data. $_SESSION and the browser's cookie remain until you clear them.
session_set_cookie_params() Sets lifetime, path, domain, secure, httponly, samesite of the session cookie; call before session_start().

Return value: the functions mostly return true on success and false on failure. session_status() returns an int.

Errors / Exceptions: session_start() returns false and raises a warning if output has already been sent; starting twice only raises a notice. Changing the ID or settings of an active session also warns.

Usage notes

  • Start the session before any output, at the top of every script that needs it. It sends a cookie, so the same rule as header() applies.
  • Regenerate the ID at login with session_regenerate_id(true) to prevent session fixation, where an attacker plants a known ID.
  • Turn on use_strict_mode (it is set in the recommended php.ini-production, but off in the built-in defaults) so the server never adopts an ID that it did not create, as the second example shows.
  • Cookie flags: set secure on HTTPS, httponly always, and samesite Lax or Strict.
  • Logout properly: clear $_SESSION, call session_destroy(), and expire the cookie with setcookie() using the parameters from session_get_cookie_params().
  • Locking: the default file handler locks the session until the script ends, so parallel requests of one visitor run one after another. Call session_write_close() once you finish writing, or use read_and_close for read-only pages.
  • Store small things: an ID, a role, a cart of IDs. Objects need their classes loaded before session_start() to unserialize.
  • Storage and cleanup: files are removed by garbage collection after session.gc_maxlifetime (1440 seconds of inactivity by default). Busy sites move sessions to Redis or a database with session_set_save_handler().
  • Timeouts: keep a last_activity timestamp in the session if you want an idle logout, because the cookie lifetime alone does not enforce it.
  • Never put the session ID in URLs. Keep session.use_only_cookies on.
  • Caching: pages that use sessions are personal; do not let a shared cache store them.