CodeIgniter use CSRF protection only in some pages

codeigniter, codeigniter-2, csrf

Solution

You can do this by editing the `config.php` file

 $config['csrf_protection'] = FALSE;

Step 1: create an array of pages that you want to protect

eg. `$csrf_pages = array('login','test');`

Step2: check if there is any request for the protected page then set it to TRUE;

if (isset($_SERVER["REQUEST_URI"])) {
    foreach ($csrf_pages as $csrf_page){
        if(stripos($_SERVER["REQUEST_URI"],$csrf_page) !== FALSE) {
            $config['csrf_protection'] = TRUE;
            break;
        }
    }

}

Step 3: add this to your views

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

Or simply use the form_open() function to add the hidden CSRF token field automatically.

Problem

What I want to do is to protect some sensitive forms from `CSRF` attack in `codeigniter` but not all pages. To protect from `CSRF` if I set it in config.php it applies for all pages. is there any way to do that only for some pages by setting in controller? ``` $config['csrf_protection'] = TRUE; ```

Original source

Related problems