设置cookie在CodeIgniter中不起作用

Der*_*der 7 codeigniter

我想用名为csrf_cookie_name的 cookie设置一个带有此函数的值$ this-> security-> get_csrf_hash(); 但是,它不起作用.

我在我的控制器中有这个:

   $csrf_cookie_value = $this->security->get_csrf_hash();
   $this->input->set_cookie('csrf_cookie_name', $csrf_cookie_value);
   echo $this->input->cookie('csrf_cookie_name'); 
   die();
Run Code Online (Sandbox Code Playgroud)

但它不起作用,没有任何回应.

如果我只尝试这个:

 $csrf_cookie_value =  $this->security->get_csrf_hash();
 echo $csrf_cookie_value;
Run Code Online (Sandbox Code Playgroud)

我工作,生成的字符串被回显.

所以,我认为接下来的两行中的某些内容是错误的:

$this->input->set_cookie('csrf_cookie_name', $csrf_cookie_value);
echo $this->input->cookie('csrf_cookie_name'); 
Run Code Online (Sandbox Code Playgroud)

谢谢你的建议.

Sil*_*u G 20

您需要指定cookie的生命周期.0将是一个会话cookie,其他任何东西都将被添加到time().

如果您未指定生命周期,CI将解释您要删除 cookie.而这正是它的作用:)

$this->input->set_cookie('name', 'value', 0);    //expires when the browser window closes
$this->input->set_cookie('name', 'value', 3600); //expires in one hour
$this->input->set_cookie('name', 'value');       //will delete the cookie (if the cookie does not exist, you will not notice anything happening)
Run Code Online (Sandbox Code Playgroud)


Jor*_*eno 7

您没有收到cookie的原因是因为该$this->input->cookie()函数直接从全局$_COOKIE数组中读取,并且$this->input->set_cookie()不会$_COOKIE立即在服务器上填充该数组.而是$this->input->set_cookie()将cookie发送回队列并存储在浏览器中.只有在用户的下一个HTTP请求中,您才能重新观察此cookie.

其次,也许更重要的是,我认为你正在使用csrf cookie不正确.要防止跨站点请求伪造,只需要启用它并在其中设置其属性config/config.php.这就对了.根本不需要在控制器中读取和写入它.