Skip to content

PHP Tutorial Sessions and Cookies

Starting a Session

Lesson 177 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Before you can use $_SESSION, you must call session_start().

index.php
PHP
<?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:

Text
PLAIN
Warning: session_start(): Session cannot be started after headers have already been sent
index.php
PHP
<?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.

bootstrap.php
PHP
<?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).

ConstantMeaning
PHP_SESSION_DISABLEDSessions are turned off
PHP_SESSION_NONESessions work, but none is started
PHP_SESSION_ACTIVEA session is started
index.php
PHP
<?php
var_dump(session_status() === PHP_SESSION_NONE);
Output
OUTPUT
bool(true)

Set options when you start

You can pass cookie options straight into session_start(). This is the safe configuration to use:

index.php
PHP
<?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

index.php
PHP
<?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.

warning
A byte order mark
Some editors save files with a hidden byte order mark (BOM) at the start. PHP counts it as output, and session_start() fails with a headers error. Save files as “UTF-8 without BOM”.