Search code examples
phpsecuritydeploymentcodeigniter-3csrf

How to enable CSRF protection in CodeIgniter 3 and use the `get_csrf_hash()` function?


I am trying to enable CSRF protection in my CodeIgniter 3 application. However, when I try to use the get_csrf_hash() function in my view file, it's not returning a value. How can I fix this issue?

When using $this->security->get_csrf_token_name() in CodeIgniter 3, only the name attribute value of the CSRF token field is being generated, while the value attribute is not being generated by using $this->security->get_csrf_hash().


Solution

  • To enable CSRF protection in your CodeIgniter 3 application, you need to do the following:

    1. Open the config.php file located in the application/config/ directory.

    2. Set $config['csrf_protection'] to TRUE to enable CSRF protection:

      $config['csrf_protection'] = TRUE;

    3. Save the config.php file.

    Note that you need to load the Form Helper and the Security Helper in your controller before you can use the form_hidden() function and the get_csrf_token_name() and get_csrf_hash() functions, respectively:

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

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