Skip to content

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

Last updated on December 2, 2022

In this post, I will show you enabling CSRF tokens 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 to show 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 the CodeIgniter form helper, you will find a hidden CSRF field in your form.

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

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

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

4 1 vote
Article Rating
Subscribe
Notify of
guest

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments