Search code examples
codeignitercsrf-protection

Codeigniter showing error when I try to resubmit form with csrf_protection set to true


My CI website has csrf protection.

$config['csrf_protection'] = TRUE;

So, when I resubmit form by refresh I am getting the following error.

The action you have requested is not allowed

Instead of showing this message, I want it to return to last page.

So, I try to override csrf_show_error() method by extending the CI_Security file.

This is my class located in application/core/My_Security.php

class MY_Security extends CI_Security {

    public function __construct()
    {
        parent::__construct();
        $this->load->library('user_agent');
    }

    public function csrf_show_error()
    {
        // show_error('The action you have requested is not allowed.');  // default code

        // force page "refresh" - redirect back to itself 
        // a page refresh restores the CSRF cookie      
        if ($this->agent->is_referral())
        {
            redirect(site_url());

        } else {            
            redirect($_SERVER['HTTP_REFERER']);         
        }        
    }
}

I am getting the following error

Call to a member function library() on a non-object


Solution

  • Insted of changing the core classes, I extended the MY_Securtiy class in core folder of application. and redirecting to past page.

    File Location: application\core\MY_Security.php

    class MY_Security extends CI_Security {
    
        public function __construct()
        {
            parent::__construct();      
        }
    
        public function csrf_show_error()
        {
            header('Location: ' . htmlspecialchars($_SERVER['REQUEST_URI']), TRUE, 200);
        }
    }