Posted by Arjun on Sunday 6th May 2018

How to Enable CSRF (Cross Site Request Forgery) in CodeIgniter

How to CodeIgniter 3

In this post, I will show you enabling CSRF token in your CodeIgniter application. To enable CSRF (Cross Site Request Forgery) protection in CodeIgniter open application/config/config.php file change $config['csrf_protection'] = FALSE; to $config['csrf_protection'] = TRUE;, change below shown other configuration values of csrf as per your needs.

| Cross Site Request Forgery
| Enables a CSRF cookie token to be set. When set to TRUE, token will be
| checked on a submitted form. If you are accepting user data, it is strongly
| recommended CSRF protection be enabled.
| 'csrf_token_name' = The token name
| 'csrf_cookie_name' = The cookie name
| 'csrf_expire' = The number in seconds the token should expire.
| 'csrf_regenerate' = Regenerate token on every submission
| 'csrf_exclude_uris' = Array of URIs which ignore CSRF checks
$config['csrf_protection'] = FALSE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();

If you create a form (form_open()) using CodeIgniter form helper, you will find a hidden CSRF filed in your form.

If you are not using CI’s form helper, hidden input field will not generate automatically you have to set it manually as shown below, past this inside your form.

<input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>" />

You might like this post - AJAX + CSRF Protection in Codeigniter ?