CSRF Protection
Generate and validate CSRF tokens in forms to prevent forged requests.
CSRF Protection is a free PHP Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What is CSRF?
Cross-Site Request Forgery (CSRF) tricks authenticated users into submitting unwanted actions. A malicious page sends a forged request to your site using the victim's active session.
How CSRF Works
Scenario: Alice is logged in to bank.com. She visits malicious.com which has a hidden form that auto-submits a transfer request to bank.com using her session cookie.
CSRF Tokens
The defence is a secret per-session token embedded in every form. The server validates the token on POST/PUT/PATCH/DELETE requests — a forged request from another origin cannot read the token.
@csrf in Laravel Blade
Add the @csrf directive to every HTML form that modifies data.
<form method="POST" action="/transfer">
@csrf
<input name="amount" type="number">
<button>Transfer</button>
</form>CSRF Middleware
Laravel's VerifyCsrfToken middleware checks the X-CSRF-TOKEN header or _token field on all non-GET requests in the web middleware group.
CSRF for AJAX
For AJAX requests, read the token from the meta tag and send it as a header.
// In the HTML head:
<meta name="csrf-token" content="{{ csrf_token() }}">
// In JavaScript (Axios):
axios.defaults.headers.common["X-CSRF-TOKEN"] =
document.querySelector("meta[name=csrf-token]").content;Excluding Routes
API routes (using Sanctum tokens) are typically excluded from CSRF protection because they use token-based auth instead of cookies.
<?php
// In VerifyCsrfToken $except:
protected $except = [
"api/*",
"webhooks/*",
];SameSite Cookie Attribute
Setting SameSite=Strict or Lax on the session cookie provides an additional CSRF defence layer in modern browsers.
Double Submit Cookie Pattern
An alternative CSRF defence for APIs: send the token as both a cookie and a request header. The server verifies they match — cross-origin requests cannot read cookies.
CSRF in API Contexts
REST APIs authenticating with Bearer tokens (Sanctum, JWT) are not vulnerable to CSRF because tokens are stored in localStorage (not sent automatically by the browser).
Testing CSRF
Laravel test helpers automatically include CSRF tokens. You can also test that unprotected POST requests are rejected.
<?php
// With token:
$this->post("/transfer", ["_token" => csrf_token(), "amount" => 100]);
// Simulating CSRF attack (no token):
$this->withoutMiddleware(VerifyCsrfToken::class)->post("/transfer", [...]);Summary
CSRF protection requires a hidden token in every state-changing form. Laravel handles this automatically with @csrf. For AJAX, add the token as an HTTP header. API routes using Bearer tokens are not affected.
Quick Check
How do you add CSRF protection to a Laravel Blade form?
Frequently asked questions
Is the “CSRF Protection” lesson free?
Yes — the full text of “CSRF Protection” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.
What will I learn in “CSRF Protection”?
Generate and validate CSRF tokens in forms to prevent forged requests. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start PHP Academy?
No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “CSRF Protection” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this PHP Academy lesson?
Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.