如何在codeigniter中设置cookie


how to set cookie in codeigniter

我尝试了以下设置cookie的代码,但无法获得cookie。

if($this->input->post('remember')){                    
                $this->load->helper('cookie');
                $cookie = array(
                        'name'   => 'remember_me',
                        'value'  => 'test',                            
                        'expire' => '300',                                                                                   
                        'secure' => TRUE
                        );
               set_cookie($cookie);                   
   }

下面的代码用于获取cookie

$cookie= get_cookie('remember_me');  
 var_dump($cookie);

有人能告诉我出了什么问题吗?提前谢谢。

使用

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

而不是set_cookie($cookie);

您需要创建一个控制器类,并向其中添加以下代码;

<?php
if ( ! defined('BASEPATH')) exit('Stop Its demostrate how to set cookie');
class cw_cookies extends CI_Controller {
   function __construct()
   {
       parent::__construct();
       $this->load->helper('cookie');
   }

   function set()
   {
       $cookie= array(
           'name'   => 'remember_me',
           'value'  => 'test',                            
           'expire' => '300',                                                                                   
           'secure' => TRUE
       );
       $this->input->set_cookie($cookie);
       echo "Congratulation Cookie Set";
   }

   function get()
   {
       echo $this->input->cookie('remember_me',true);
   }
}

上面的代码通过设置cookie

$this->input->set_cookie()

使用加载帮助程序

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

您可以在以下位置阅读更多信息:在Codeigniter 中设置Cookie

    public function cookie()
    {
        $this->load->helper('cookie');
        $name   = 'user';
        $value  = 'pradip';
        $expire = time()+1000;
        $path  = '/';
        $secure = TRUE;
        setcookie($name,$value,$expire,$path); 
        $this->load->view('welcome_message');
    }

调用视图页面,如echo $this->input->cookie('user');

输出=pradip

说出数据

$my_cookie= array(
       'name'   => 'remember_me',
       'value'  => 'test value',                            
       'expire' => '3000',                                                                                   
       'secure' => TRUE
   );

使用

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

而不是

set_cookie($my_cookie);

首先将此行添加到控制器的顶部

function __construct(){
    parent::__construct();
    $this->load->helper(array('cookie', 'url'));
}

然后将cookie设置为

set_cookie('counters','ok','999600');