Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent from displaying the default CSRF error page in Codeigniter

I don't like how CI behaves by default when a CSRF token has expired. For instance, when a user has displayed the login form for a long time and they finally submit it, this ugly blank page with the error message comes up.

I asked for ways to get around this, and someone told me to extend the Security class, and override its csrf_show_error() method, like this:

class MY_Security extends CI_Security {


    public function __construct()
    {
        parent::__construct();

    }

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

        // add redirect actions here
        // I'd like to use some helper function here like redirect()

    }

} 

The problem is that I can't, or I don't know how to get access to the libraries and helpers from here, in order to perform a redirect. I can't use the get_instance() function here because I get an error. So, what else couls I do? Or is there any other better option to prevent from showing this error page?

like image 739
Luis Martin Avatar asked Jan 18 '13 20:01

Luis Martin


3 Answers

Core classes like CI_Security are instantiated before helpers and libraries - there is no ability to utilize these functions like you would elsewhere in a CI app.

You'll have to duplicate the functionality in the class using native PHP functions like header() which is not much of a hardship if you'd simply like to redirect to a prettier error page.

like image 189
SLD Avatar answered Oct 23 '22 10:10

SLD


One of a way to do is extend Security class to redirect to the same page.

CodeIgniter User Guide - Extending Core Class

Nice explanation of How to handle an expired CSRF token after a page is left open

like image 26
Maduka Jayalath Avatar answered Oct 23 '22 09:10

Maduka Jayalath


For those who want change the page view, you can edit the file error_general.php in /application/errors/error_general.php. CodeIgniter uses that file to show general errors, like CSRF Errors.

Regards :).

like image 2
Gerardo Avatar answered Oct 23 '22 10:10

Gerardo