After this lesson you can build a book form that submits through a POST route protected by CodeIgniter's CSRF filter. CSRF protection addresses forged browser requests that rely on ambient credentials. It does not validate the title and does not decide whether a visitor is allowed to edit the catalogue.
Keep the form and its submission separate
The existing GET books/new route will display the form. Add this POST declaration to Routes.php for submission. Do not use a general route accepting every method for a write action.
$routes->post('books', 'Books::create', ['filter' => 'csrf']);The starter already defines the csrf alias in app/Config/Filters.php. Attaching it to this route activates it for the submission. Do not assume an alias being present means the filter is active everywhere. Inspect the actual route and its effective filters.
In Books, add this method for the form page:
public function new(): string
{
helper('form');
return view('books/form', ['errors' => []]);
}The create method arrives in the validation lesson immediately after this one. Until it exists, inspect the form and filter configuration without treating a failed submission as a completed feature. Learning in stages means each stage has a precise expected boundary.
Create an accessible HTML form
Create app/Views/books/form.php with this template. The token field is generated by the framework rather than a hard-coded value copied from one browser request.
<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>
<h1>Add a book</h1>
<?php foreach ($errors as $error): ?><p role="alert"><?= esc($error) ?></p><?php endforeach ?>
<form action="<?= esc(site_url('books'), 'attr') ?>" method="post">
<?= csrf_field() ?>
<label for="title">Title</label>
<input id="title" name="title" maxlength="120" required>
<button type="submit">Add book</button>
</form>
<?= $this->endSection() ?>The template and controller fragment passed PHP lint. The label connects to the input identifier. The name attribute determines the submitted field key. The maxlength and required attributes help browser users, but a caller can bypass them, so the server still needs validation.
The form helper is loaded before rendering. csrf_field generates the hidden token input. The action is a fixed application URL escaped for an attribute. Error strings are escaped as text. The form intentionally does not repopulate submitted values yet; if you add that convenience, escape the value for its attribute context and never repopulate passwords or other sensitive fields indiscriminately.
Understand the CSRF boundary
CodeIgniter's Security documentation describes cookie-based and session-based protection and configuration options. The verified starter used its default configuration for this local exercise. When designing a session-authenticated application, review the documentation's session-based guidance and align the protection method with the authentication design. Do not change token settings merely to avoid a failing test.
Tokens must be generated for the current client flow. Token regeneration can matter when several forms or asynchronous requests are open. A stale token is a reason to understand the lifecycle, not to disable the filter. Similarly, an API's authentication model must be considered before deciding whether a browser-oriented CSRF policy applies.
CSRF failure behavior can include a redirect in production configuration. During local verification, a tokenless submission was rejected before inserting its title, but following the redirect produced an ordinary page response. Therefore a client's final HTTP 200 alone does not prove that a write was accepted. Inspect redirect history and database effects when testing rejection paths.
Verify the effective filter
php spark filter:check post booksExample output captured on 2026-11; yours will differ. This is an excerpt of the effective filter list.
Before Filter Classes:
CodeIgniter\Filters\ForceHTTPS → CodeIgniter\Filters\PageCache → CodeIgniter\Filters\CSRFThe route-specific CSRF check works alongside required filters. Keep auto routing disabled so that another route cannot unintentionally bypass the protected entry point. A hidden field without an active filter is not protection, and a filter without a usable token flow prevents legitimate submissions.
The fetched official Security guide and Form Helper guide document these mechanisms. The course's local form uses no real accounts and is not an authorized public catalogue editor.
Common mistakes
Hard-coding a token makes it stale or unrelated to the current client. Using GET for a mutation falls outside the intended CSRF-protected write flow. Treating required as server validation trusts the browser too much. Finally, assuming a token proves permission confuses request origin protection with authorization. Both boundaries matter, and neither replaces escaping.
Exercise
Identify the form's submitted title key and the code that generates its token. Explain why an attacker who can submit their own valid token still must not gain permission to change a real catalogue. Predict why a rejected request might end at an HTTP 200 page after redirects.
Show an answer
The input name is title and csrf_field generates the token input. CSRF checks do not grant editor rights; authorization must separately decide who can write. Production failure handling may redirect to a normal page, so a final successful page response is not evidence of an accepted database mutation.
Previous lesson · Next lesson · Related: explicit routes · Related: security boundaries
Key points
- Enable the CSRF filter on the actual write route.
- Browser input attributes do not replace server validation.
- A followed redirect can hide the original rejection response.