agyanadda@gmail.com

CodeIgniter 4 Security: CSRF, XSS and SQL Injection

Forms, Sessions and Security 1 min read Updated Dec 3, 2026 Topic 23 of 30

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 = production on live servers (hides error details)
  • Validate all input; list $allowedFields in models
  • secureheaders filter adds security headers; honeypot filter stops simple spam bots
  • Set app.forceGlobalSecureRequests = true to force HTTPS
  • Keep CodeIgniter updated with composer update

Example

Example — Enable CSRF and use it in forms and AJAX PHP
<?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().

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which function adds the hidden CSRF field to a form?

Exercise 2 True / False

CSRF protection is enabled automatically in every new CodeIgniter 4 project.

Exercise 3 Fill in the Blank

Escape output in views with the ___() function.

Frequently Asked Questions

The form is missing csrf_field(), or the token expired because the page was open too long. Add csrf_field() (or use form_open()), and for AJAX send the current csrf_hash() with each request.