CodeIgniter 4 gives you strong security tools — but some must be switched on.
CSRF protection
CSRF attacks trick a logged-in user's browser into submitting a form. Enable the csrf filter in app/Config/Filters.php, in $globals['before'] (it is commented out in a new project). Then add <?= csrf_field() ?> to every form (form_open() adds it automatically). For AJAX, send the token from csrf_hash() with the request.
XSS (cross-site scripting)
Escape everything you print: <?= esc($comment) ?>. Use esc($value, 'attr') inside attributes and esc($value, 'js') inside JavaScript.
SQL injection
Use the Query Builder or models, which escape values. For raw SQL, always use bindings: $db->query('... WHERE id = ?', [$id]). Never join user input into SQL strings.
Passwords
password_hash() and password_verify() only.
More protection
CI_ENVIRONMENT = productionon live servers (hides error details)- Validate all input; list
$allowedFieldsin models secureheadersfilter adds security headers;honeypotfilter stops simple spam bots- Set
app.forceGlobalSecureRequests = trueto force HTTPS - Keep CodeIgniter updated with
composer update
Example
<?php
// app/Config/Filters.php
public array $globals = [
'before' => [
'csrf', // <- uncomment / add this
// 'honeypot',
],
'after' => [
// 'secureheaders',
],
];
// In a form view:
// <form method="post" action="<?= site_url('comments') ?>">
// <?= csrf_field() ?>
// <textarea name="comment"></textarea>
// <button>Post</button>
// </form>
// Printing user content safely:
// <p><?= esc($comment['text']) ?></p>
// AJAX (JavaScript) - send the token with the request:
// fetch('/comments', {
// method: 'POST',
// headers: { 'X-Requested-With': 'XMLHttpRequest' },
// body: new URLSearchParams({ comment: 'Hi', '<?= csrf_token() ?>': '<?= csrf_hash() ?>' })
// });
With the csrf filter on, a POST without a valid token is rejected with an error. A comment like <script>alert(1)</script> is shown as text, not run, because of esc().