Sessions

Sessions in production: lifecycle, regeneration, and fixation risks.

On this page

What Sessions Are

Sessions store server-side state for a user. The browser keeps only a session ID cookie. Data itself lives on the server.

Starting a Session

You must call session_start() before accessing $_SESSION.

<?php
session_start();
$_SESSION["user_id"] = 1;

Reading Session Data

<?php
session_start();

$userId = $_SESSION["user_id"] ?? null;
if (!$userId) {
  echo "Not logged in";
}

Session Fixation Protection

After login, regenerate the session ID to prevent fixation attacks.

<?php
session_start();

// after successful login
session_regenerate_id(true);
$_SESSION["user_id"] = $userId;

Destroying a Session

<?php
session_start();
$_SESSION = [];
session_destroy();

Production Tip

Set secure cookie parameters (Secure, HttpOnly, SameSite) and use HTTPS. Never store sensitive data like raw passwords in sessions.