📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials CodeIgniter 4 CSRF and Security CI4

CSRF and Security CI4

5 min read
Enable CSRF filter, escape output with esc(), use honeypot, and force HTTPS in CI4 apps.

Security in CI4

// CSRF is enabled by default in app/Config/Security.php
public string $csrfProtection = "cookie";  // or "session"
public array  $excludeURIs    = ["api/.*"];

// In forms — auto adds CSRF field
<?= form_open("posts/store") ?>
    <input name="title">
    <button type="submit">Save</button>
<?= form_close() ?>

// Or manually
<input type="hidden" name="<?= csrf_token() ?>" value="<?= csrf_hash() ?>">

// Output escaping — always escape output!
echo esc($user["name"]);         // HTML context
echo esc($url, "url");           // URL context
echo esc($css, "css");           // CSS context
echo esc($attr, "attr");         // attribute context

// Content Security Policy
// app/Config/ContentSecurityPolicy.php

// Honeypot filter — catches bots
// app/Config/Filters.php
public array $globals = ["before" => ["honeypot"]];