Sessions

A session keeps a visitor's data on the server and links it to the browser with one cookie holding the session id.

Syntaxsession_start(array $options = []): bool

A cookie can carry a visitor's data, but the visitor can edit it. A session turns that around. The data stays on the server, and only a long random session id travels in a cookie.

How it works

session_start() looks for that cookie, named PHPSESSID by default. If it finds a known id, PHP loads the stored data for it into $_SESSION. If not, it generates a new id and sends it as a cookie. Because it sends a header, it must run before any output.

$_SESSION is then an ordinary array. Whatever it holds when the script ends is written back to the store. By default the store is one file per session, in the directory named by session.save_path.

One request at a time

PHP locks a session while a request is using it, so a second request from the same visitor waits its turn. A page that does slow work after it has finished with the session should call session_write_close() to release the lock early. $_SESSION stays readable after that, but further changes are not saved.

What trips people up

Session data is not storage. It is cleared some time after session.gc_maxlifetime seconds without use, 1440 by default, no matter what expiry the cookie carries. Anything that must still be there tomorrow belongs in a database.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Keep a signed-in visitor signed in from page to page.
  • Show a confirmation message after a form redirect.
  • Hold a multi-step form's answers until the final step.
  • Release the session lock before a slow export so the visitor's other tabs do not hang.

More examples

A page that counts visits

The real calls, as you would write them in a page. Note the ?? on both reads: on the first request of a visit the session is empty, so every key has to have a default. The name came from the visitor at some point, so it is escaped on the way out even though it was read from the server's own store.

Example · php
<?php

declare(strict_types=1);

// Nothing may be printed before this line.
session_start();

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

echo '<p>Hello ' . htmlspecialchars($name, ENT_QUOTES) . '.</p>';
echo '<p>Page views this visit: ' . $_SESSION['views'] . '</p>';

Cookie options, longhand and shorthand

PHP's session cookie is a cookie like any other, and it needs the same flags. These two blocks produce the same cookie: session_set_cookie_params() before the start, or the equivalent keys passed straight to session_start(). Any session.* setting can go in that array, which is how you override php.ini from code.

Example · php
<?php

declare(strict_types=1);

// Longhand: set the cookie options, then start the session.
session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Lax',
]);
session_start();

// Shorthand for the same thing, in one call. The keys are the session.*
// ini names with the "session." prefix dropped. Use one form or the other,
// not both.
session_start([
    'cookie_lifetime' => 0,
    'cookie_path' => '/',
    'cookie_secure' => true,
    'cookie_httponly' => true,
    'cookie_samesite' => 'Lax',
]);

A one-time message after a redirect

The flash message pattern. A form handler cannot print a confirmation and redirect at the same time, so it stores the message in the session and the destination page prints it. The unset is the whole trick: without it the message reappears on every page load until the session ends.

Example · php
<?php

declare(strict_types=1);

session_start();

// An earlier page set $_SESSION['flash'] and then redirected here.
// Read it and remove it, so a refresh does not show it again.
if (isset($_SESSION['flash'])) {
    echo '<p>' . htmlspecialchars($_SESSION['flash'], ENT_QUOTES) . '</p>';
    unset($_SESSION['flash']);
}

Discussion

  • Be the first to comment on this lesson.