当我尝试重新提交 csrf_protection 设置为 true 的表单时,Codeigniter 显示错误

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

我的 CI 网站有 csrf 保护。

$config['csrf_protection'] = TRUE;

因此,当我通过刷新重新提交表单时,出现以下错误。

The action you have requested is not allowed

我不想显示此消息,而是希望它 return 到最后一页。

因此,我尝试通过扩展 CI_Security 文件来覆盖 csrf_show_error() 方法。

这是我位于 application/core/My_Security 的 class。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']);         
        }        
    }
}

我收到以下错误

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

为了改变核心 classes,我扩展了应用程序核心文件夹中的 MY_Securtiy class。并重定向到过去的页面。

文件位置: 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);
    }
}

感谢您的解决方案,但通过将新请求的请求类型更改为 GET,使用 return 代码 302 似乎更好,而不管原始请求中使用的类型(例如 POST).下次刷新不会问任何问题