Lesson 8 of 8
Not started

CSRF Protection and Secure HTTP Headers

Stop forged requests with CSRF tokens and harden responses with security headers.

Cross-Site Request Forgery (CSRF)

CSRF tricks a logged-in user's browser into submitting an action they did not intend — for example, a hidden form on a malicious site that posts to your /transfer endpoint using the victim's session cookie.

The token defense

Issue a unique, unpredictable token per session (or per form) and require it on every state-changing request:

// On render
$_SESSION['csrf'] = $_SESSION['csrf'] ?? bin2hex(random_bytes(32));
// In the form
echo '';

// On submit
if (!hash_equals($_SESSION['csrf'], $_POST['csrf'] ?? '')) {
http_response_code(403);
exit('Invalid CSRF token');
}

Also set cookies with SameSite=Lax (or Strict) so they are not sent on cross-site requests.

Security headers worth setting

  • Strict-Transport-Security — force HTTPS for future visits.

  • Content-Security-Policy — restrict script/style sources.

  • X-Content-Type-Options: nosniff — stop MIME sniffing.

  • Referrer-Policy: strict-origin-when-cross-origin — limit referrer leakage.

  • X-Frame-Options: DENY — prevent clickjacking (or use CSP frame-ancestors).

What it means for you

CSRF tokens protect your users' actions; security headers harden every response with a few lines of config. Together they are cheap, high-value defenses that belong on every PHP app.