Skip to content

Discover CSRF Protection In Codeigniter

Reading Time: 2 minutes

CSRF protection

In this article, we will learn how to painlessly protect your CodeIgniter (pre 2.0) application against Cross-Site Request Forgery attacks.

CSRF is an inbuilt feature in Codeigniter. To enable CSRF protection you just need to enable it under the config file. Once it has been enabled all the forms will be secured.

CSRF Token:

Protecting your CodeIgniter application from Cross-site request forgery (CSRF or XSRF) attacks is pretty easy thanks to the built-in support. Once CSRF protection is enabled in the config file, you can use the form helper or custom code to protect your forms and AJAX calls from CSRF. The CodeIgniter framework will automatically protect forms or calls that make POST requests once protection is enabled – here’s how to update your application.

Cross-Site Request Forgery token is a hash string that includes each form request and its submission. It will check with an already generated token in the session. If both the value is matched it will accept your request else it will be declined. Here in Codeigniter CSRF value is added in the hidden input field and sent with post requests.

Enable CSRF protection in Codeigniter:

CSRF Protection in Codeigniter

To enable CSRF protection in your CodeIgniter application, edit the application/config/config.php file and look for $config['csrf_protection']. Change the setting to TRUE (if it isn’t already) to enable protection. If you then test a form or AJAX call in your application, the request will fail to show a generic error:

See also  How to use PHP Composer

Go to application/config/config.php and check for CSRF Settings.

$config['csrf_protection'] = TRUE; // changed FALSE to TRUE
$config['csrf_token_name'] = 'csrftest_name';
$config['csrf_cookie_name'] = 'csrfcookie_name';




Use CSRF Token:

The easiest way to update your forms is to use the Form Helper. Load the form helper manually (in your controller) or add it to the application/config/autoload.php file and call echo form_open('login'); (the first parameter is the form action, and the second parameter is an array of attributes): Form Helper: Codeigniter has its own functions and fields to make form and fields. The form can be rendered to view using :

$this->load->helper('form');

Leave a Reply