Search code examples
phpformscodeignitercsrf

Enabling CSRF to TRUE in CodeIgniter


Just read that CodeIgniter 2.x has built-in CSRF protection. Now upon reading the documentation, I didn't found anything relating CSRF, just an option of setting it to TRUE in the config.php file then that's it. However, in my system I don't use this form_helper which automatically incorporates the CSRF protection of the CodeIgniter, instead I have the native <form> of HTML.

My concern is do I need to do anything to implement the CSRF of CodeIgniter, or just setting the option to TRUE is enough?


Solution

  • To enable CRSF in Codeigniter all you need to do is:

    1. Set the option to "TRUE" in the config file

    2. All your forms MUST use the form_open() helper function. This will automatically generate and include a 'hidden' CSRF token in your forms. Codeigniter will then automatically check this token on each form submission as part of the security funciton. If it detects a CSRF error, it will throw a 401 error automatically.

    You dont need to do anything else.

    edit: I just re-read that you do not use form_open(). It might be possible to manually insert the CSRF token into the forms yourself - but it would be more work than is required. Just convert all your forms to use form_open - and it will work seemlessly.

    (And yes - this is one of the few poorly documented features in CI - so I understand why you couldnt find the answer - it took me a while as well)