PHP 8: Modern PHP Development · Security for PHP Applications

Sessions and Cookies

Configure secure sessions and cookies for PHP apps.

PHP sessions store a session ID in a cookie and data on the server (files by default; Redis or a database when running multiple servers). Harden them with session.cookie_secure=1, session.cookie_httponly=1, session.cookie_samesite=Lax, session.use_strict_mode=1 and session.use_only_cookies=1. Regenerate the ID on privilege changes, set idle and absolute timeouts, and destroy the session fully on logout.

<?php
session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Lax',
]);
ini_set('session.use_strict_mode', '1');
session_start();

// Logout
$_SESSION = [];
$params = session_get_cookie_params();
setcookie(session_name(), '', ['expires' => time() - 3600] + $params);
session_destroy();

Common pitfalls

  • File-based sessions behind a load balancer without sticky sessions — users get logged out randomly.
  • Storing large objects in the session.
  • Not invalidating the session server-side on logout.

Key points

  • Secure, HttpOnly, SameSite cookies
  • Shared session storage for multiple servers
  • Regenerate on login; destroy on logout

Further reading: PHP manual: session security

Practice questions

Why do file-based sessions break with multiple web servers?

Answer

Each server stores sessions on its own disk, so a request routed to another server can't find the session. Use Redis/Memcached/DB session handlers (or sticky sessions as a stopgap).

What does session.use_strict_mode protect against?

Answer

It makes PHP reject uninitialized session IDs supplied by the client, mitigating session fixation where an attacker plants a known ID.

Open in the app to mark lessons complete, take notes and track your progress.