无法在Code-igniter中设置cookie

时间:2016-10-03 10:06:57

标签: php cookies codeigniter-3

我无法生成Cookie,以下代码仅适用于其他部分。

public function set(){
          $cookie = array(
              'name' => 'demo',
              'value' => 'hello i m saved cookie',
              'expire' => '86500'

          );//EOF array
          if($this->input->set_cookie($cookie))
          {
             $data = array( 'message' => 'cookie successfully set');
              $this->load->view('cookies_view',$data);
          }
          else{
              $data = array( 'message' => 'Something went wrong while creating cookie');
              $this->load->view('cookies_view',$data);
          }

3 个答案:

答案 0 :(得分:1)

您的值已经存储在Cookie $this->input->set_cookie($cookie)中,这只会创建Cookie。如果你想检查或不检查cookie值,你可以这样使用:

$cookie = array(
  'name'   => 'demo',
  'value'  => 'Hello i m cookies which saved in this broswer',
   'expire' => '86500',
);
$this->input->set_cookie($cookie);

if(isset(get_cookie('demo'))){ // check cookie value
  echo "success"; // replace with your code
}
else{
  echo "failed"; // replace with your code
}

get_cookie('demo')将返回Cookie值。

您还可以浏览CI Manual

确保您在文件中使用cookie帮助程序,您必须包含cookie帮助程序:

$this->load->helper('cookie');

答案 1 :(得分:1)

$this->input->set_cookie($cookie); 

此函数返回NULL,这就是为什么你的条件不能正常工作。你的cookie正在设置

使用$this->input->cookie('your cookie name')检查您的病情

public function set()
{
    $this->load->helper('cookie');
    $cookie = array(
      'name'   => 'demo',
      'value'  => 'Hello i m cookie',
      'expire' => '86500'
    );
    $this->input->set_cookie($cookie);
    if ($this->input->cookie('demo')) {
        $data['data'] = array('message' => 'cookie successfully set');
        $this->load->view('your view', $data);
    } else {
        $data['data'] = array('message' => 'Something went wrong while creating cookie');
        $this->load->view('your view', $data);
    }
}

答案 2 :(得分:0)

在经过数小时的调试后,我意识到对于本地开发,cookie_secure设置为true。

因此,请进行简单检查;

如果domain不是https,并且在config.php中将cookie_secure设置为TRUE,则不会直接设置cookie。更改为FALSE,它将同时在http和https中设置。