Php 设置配置项(csrf)在Codeigniter中不起作用

Php 设置配置项(csrf)在Codeigniter中不起作用,php,codeigniter,config,csrf,Php,Codeigniter,Config,Csrf,我只想在我的几个控制器上启用csrf保护,所以我 function __construct() { parent::__construct(); $this->load->library('form_validation'); $this->load->library('tank_auth'); $this->load->helper(array('form', 'url')); $this->l

我只想在我的几个控制器上启用csrf保护,所以我

function __construct() {

    parent::__construct();
    $this->load->library('form_validation');        
    $this->load->library('tank_auth');
    $this->load->helper(array('form', 'url'));
    $this->load->model('user_model', '', true);

    $this->config->set_item('csrf_protection', TRUE);

}
但它似乎不起作用,尽管当我在页面上执行var_dump($this->config)时,它显示csrf_保护是正确的,但是cookie没有设置,表单有一个没有值的隐藏字段

Csrf令牌名称和cookie名称都已设置,使用form_open()调用表单

任何帮助都将不胜感激

更新:因此从版本2.1.1开始这是不可能的,因为安全类构造中的行
if(配置项('csrf\u保护')==TRUE){


安全类在控制器之前初始化,因此控制器中的配置项更改自然不会影响它。

我为您提供了一个解决方案。创建一个自定义应用程序/core/MY_Security.php并将其放入其中:

<?php if ( !defined( 'BASEPATH' ) ) exit( 'No direct script access allowed' );

class MY_Security extends CI_Security
{
    public function csrf_verify( )
    {
        foreach ( config_item('csrf_excludes') as $exclude )
        {
            $uri = load_class('URI', 'core');
            if ( preg_match( $exclude, $uri->uri_string() ) > 0 )
            {
                // still do input filtering to prevent parameter piggybacking in the form
                if (isset($_COOKIE[$this->_csrf_cookie_name]) && preg_match( '#^[0-9a-f]{32}$#iS', $_COOKIE[$this->_csrf_cookie_name] ) == 0)
                {
                    unset( $_COOKIE[$this->_csrf_cookie_name] );
                }
                return;
            }
        }
        parent::csrf_verify( );
    }
}
每个匹配的URL模式都将从CSRF检查中排除。您可以在以下位置构建正则表达式:


干杯

在加载表单帮助程序之前,请尝试设置配置项?您好!感谢您的快速回答,不幸的是,这并没有解决问题,我已将set_项放在parent::constructCSRF protection作为核心的一部分之后,并在处理任何控制器之前初始化。如果您想这样做,并且正在运行CI2.x,您可能需要在
application/core
中使用
MY_Security.php
文件修改core,并在其中提供您的逻辑,以便将CSRF应用于特定控制器。如果您正在运行CI 3.x,您需要读取和检查该文件
system/core/Security.php
,它有一个新的配置项
$config['CSRF\u exclude\u uris']=array()
这正是你想要的。但它只在CI 3.xHi中!谢谢你的回答。问题是,我知道它应该可以工作。在我的几个其他项目中,它工作得很好,我将csrf_保护设置为false,并在特定页面上使用set_项打开它。我将临时修改我的核心文件,直到找到一个工作的解决方案没关系。我发现在我的另一个项目中,安全类构造没有if(config_item('csrf_protection')==TRUE)行它一定是在更高版本中添加的。您好!感谢您的回答,我确实这样做了。我将CI 3.0的安全类复制到了我的\u安全类中,因为它已经可以使用$config['CSRF\u exclude\u uris']关闭特定URL的CSRF保护,对于将来迁移到CI 3.0来说,这是一个更简单的解决方案。但您的解决方案也很好,谢谢!
$config['csrf_excludes'] = array
    ( '@^/?excluded_url_1/?@i'
    , '@^/?excluded_url_2/?@i' );