What is CSRF protection in CodeIgniter 4?
Why Interviewers Ask This
Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for CodeIgniter development. It reveals whether you understand the building blocks that more complex concepts rely on.
Answer
CodeIgniter 4 provides built-in CSRF protection via the Security filter. Enable in app/Config/Security.php: $csrfProtection = "cookie" (or "session"). Apply the Security filter globally in app/Config/Filters.php or per route. In HTML forms, include the CSRF field: <?= csrf_field() ?> — generates a hidden input with the token. Or manually: <input type="hidden" name="<?= csrf_token() ?>" value="<?= csrf_hash() ?>">. For AJAX requests, include the token in headers or request body. If validation fails, a 403 response is returned. Exclude specific routes from CSRF: add them to the $except array in the Security configuration (useful for webhook endpoints that receive external POST requests).
Common Mistake
Many candidates answer correctly but can't explain the 'why'. Always be prepared to justify your answer with a concrete example or use case from your CodeIgniter experience.
Previous
What is the Email library in CodeIgniter 4?
Next
What is the File Upload class in CodeIgniter 4?