Before you can use $_SESSION, you must call session_start().
<?php
session_start();
$_SESSION["visits"] = ($_SESSION["visits"] ?? 0) + 1;
echo "You have visited " . $_SESSION["visits"] . " time(s).";
Reload the page, and the number goes up. PHP remembers it for your browser.
What session_start() does
- If the browser sent a valid session cookie, PHP loads that session into
$_SESSION. - If not, PHP creates a new session and sends a cookie with its ID.
Call it before any output
session_start() sends a cookie, and cookies are part of the HTTP headers. Headers must be sent before any content. If anything has already been printed (a space, a blank line, HTML), PHP warns:
Warning: session_start(): Session cannot be started after headers have already been sent
<?php
echo "Hello"; // output starts here
session_start(); // too late: this fails
Put session_start() at the very top of the file, before the HTML.
A bootstrap file
Most projects start the session in one shared file, so it is never forgotten.
<?php
declare(strict_types=1);
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
Every page begins with require_once __DIR__ . "/bootstrap.php";.
Check the status
session_status() tells you whether a session is active, which avoids starting it twice (a notice).
| Constant | Meaning |
|---|---|
PHP_SESSION_DISABLED | Sessions are turned off |
PHP_SESSION_NONE | Sessions work, but none is started |
PHP_SESSION_ACTIVE | A session is started |
<?php
var_dump(session_status() === PHP_SESSION_NONE);
bool(true)
Set options when you start
You can pass cookie options straight into session_start(). This is the safe configuration to use:
<?php
session_start([
"cookie_httponly" => true,
"cookie_secure" => true, // only over HTTPS
"cookie_samesite" => "Lax",
"use_strict_mode" => true,
]);
What each option means is explained in Secure Session Practices.
The session ID
<?php
session_start();
echo session_id(); // a long random string
echo session_name(); // PHPSESSID
You will rarely need the ID itself. Never print it, log it or put it in a URL.
Sessions on the command line
Sessions need a browser and cookies, so session_start() does not behave the same in a terminal script. We write the examples as web pages for that reason.
A byte order mark
session_start() fails with a headers error. Save files as “UTF-8 without BOM”.