iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PHP Sessions

A session stores data on the server, keyed by an ID that's sent to the browser as a cookie. PHP wires this all up for you — call session_start() and use $_SESSION.

Basic usage

PHP
session_start();

$_SESSION['visits'] = ($_SESSION['visits'] ?? 0) + 1;
echo 'visits: ', $_SESSION['visits'];

Login flow

PHP
session_start();

// After verifying credentials
$_SESSION['user_id'] = $user->id;
session_regenerate_id(true);     // mitigate session fixation

// Later requests
if (!isset($_SESSION['user_id'])) {
    header('Location: /login');
    exit;
}

Logout

PHP
session_start();
$_SESSION = [];                                  // clear data
setcookie(session_name(), '', time() - 3600);    // delete cookie
session_destroy();                                // destroy file

Configure for safety

PHP — php.ini
session.cookie_secure   = 1     ; HTTPS only
session.cookie_httponly = 1     ; JS cannot read
session.cookie_samesite = "Lax" ; CSRF mitigation
session.use_strict_mode = 1     ; refuse uninitialised IDs
session.gc_maxlifetime  = 1440  ; seconds (24 min)

Where sessions are stored

By default, PHP writes session files into session.save_path. For multi-server deployments swap to Redis or a database via session.save_handler.

Common gotchas

  • session_start() must run before any output.
  • Anything you stuff into $_SESSION is serialised; objects must be safely serialisable.
  • Don't store huge blobs in the session — slows every request.
  • Always session_regenerate_id(true) at login to defend against fixation.
Tip: In a framework (Laravel, Symfony), don't touch $_SESSION directly. Use the framework's session API — it handles drivers, regeneration, encryption, and middleware ordering for you.

Example

Example
<?php
session_start();
$_SESSION['visits'] = ($_SESSION['visits'] ?? 0) + 1;
echo 'visits: ', $_SESSION['visits'];
Try it Yourself »

Exercise

Open the session before reading $_SESSION.

();

Test yourself

Q1. Start a session with…
Q2. After login, call…
Q3. Default storage…

Discussion

Loading…