PHP 8 interview question · Most asked

How do you protect a PHP app against CSRF and session attacks?

Summary

Use per-session CSRF tokens on state-changing requests, SameSite cookies, session_regenerate_id(true) on login, and secure cookie flags (Secure, HttpOnly).

Longer Answer

CSRF: generate bin2hex(random_bytes(32)), store it in the session, embed it in forms, and compare with hash_equals(). SameSite=Lax blocks most cross-site POSTs. Session fixation: regenerate the ID after authentication or privilege change. Also set session.use_strict_mode=1 and session.cookie_secure=1, and expire idle sessions server-side.

Code Example

<?php
session_set_cookie_params(['secure' => true, 'httponly' => true, 'samesite' => 'Lax']);
session_start();
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));

if ($_SERVER['REQUEST_METHOD'] === 'POST'
    && !hash_equals($_SESSION['csrf'], $_POST['csrf'] ?? '')) {
    http_response_code(419);
    exit('Invalid CSRF token');
}

Key Points

  • Token + hash_equals() for CSRF
  • SameSite=Lax/Strict cookies
  • session_regenerate_id(true) on login
  • session.use_strict_mode=1

More most-asked PHP 8 questions

← All PHP 8 questions