How do PHP sessions work?

PHP & the Web 2 min read Full lesson: Building a PHP Web Form
Short answer

Call session_start() before any output, then read and write $_SESSION like an array. PHP stores the data server-side and gives the browser only an ID in a cookie.

php
session_start();

$_SESSION['user_id'] = 42;
$_SESSION['name'] = 'Dom';

// on any later page
session_start();
echo $_SESSION['name'] ?? 'guest';

#What is actually happening

  1. session_start() looks for a session cookie (default name PHPSESSID).
  2. If there is none, PHP generates an ID and sends it as a cookie.
  3. The data lives in a file on the server, keyed by that ID.

The browser never sees the contents — only the ID. That is what makes sessions suitable for things a cookie should not hold.

#session_start() must come before output

It sends a cookie header, so the same "headers already sent" rule applies. Put it at the very top of the file.

#Logging in and out

php
// On successful login — regenerate to prevent session fixation
session_regenerate_id(true);
$_SESSION['user_id'] = $user['id'];

// Logging out
$_SESSION = [];
session_destroy();

session_regenerate_id(true) is the line people omit. Without it, an attacker who can set a victim's session ID before login retains a valid session afterwards.

In php.ini or before session_start():

php
session_set_cookie_params([
    'httponly' => true,     // JavaScript cannot read it
    'secure'   => true,     // HTTPS only
    'samesite' => 'Lax',    // blocks most CSRF
]);

#Sessions are not a database

$_SESSION is loaded and written on every request. Keep it to identifiers and small flags — a user ID, a cart ID, a CSRF token. Look the rest up when you need it.