Codeigniter cookie已设置,但返回NULL


Codeigniter cookie is set but returns NULL

我只是不明白为什么我的cookie返回NULL值。我想我已经在设置cookie时设置了正确的语法,我已经检查了if条件,没有问题。配置文件中的global_xss_filtering选项是否相关?必须将其设置为true才能使cookie在中工作

如果有人能指出我的错误,我很高兴。

我的控制器

    public function store_cookie(){
            if($this->input->post('remember_me') == 'remember'){
                                $cookie = array(
                                'name'   => 'remember',
                                'value'  => 'logged_in',
                                'expire' => '86500',
                                'secure' => TRUE
                                );
                            $this->input->set_cookie($cookie);
                            var_dump($this->input->cookie($cookie));
                            //This is where i do my checking and it returns NULL
                            die(); 
                            //model
                            $this->load->model('admin_model');
                            $this->admin_model->store_cookie($this->input->post('email'),$this->input->post('remember_me'));
                            }
                }

public function validate_credentials2(){
        $this->load->model('admin_model');
        $query = $this->admin_model->validate();
        if($query){
                // if($this->input->post('remember_me')== 'remember'){
                //  $cookie = array(
                //         'name'   => 'remember',
                //         'value'  => 'logged_in',
                //         'expire' => '86500',
                //         'secure' => TRUE
                //  );
                // $this->input->set_cookie($cookie);
                // }
                $this->store_cookie();
                $data = array(
                    'email' => $this->input->post('email'),
                    'is_logged_in' => TRUE,
                    'role' => 'admin'
                    );
                $this->session->set_userdata('counter2', 0);
                $this->session->set_userdata($data);
                redirect('admin/home', 'refresh');
}
//admin controller
public function home(){
             var_dump($this->input->cookie('remember')); //still returns NULL
             die(); 
            $this->load->view('ui/admin_home');
        }

我找到了问题的解决方案。

我将过期时间设置为数值,将安全性设置为false。

来源:https://stackoverflow.com/a/9200289/4779791

检查文档

'secure' => TRUE

仅适用于https。。。

还添加路径和域作为

'domain' => '.localhost',
'path'   => '/path_to_the_folder_name',

您必须将用户id存储在cookie中,当页面打开时。。。在检查会话之前检查Cookie。。。

如果在cookie中设置了用户id。。。在会话中获取用户并设置用户。。。

//admin controller
public function home(){
         var_dump($this->input->cookie('remember')); //still returns NULL
             die(); 
          $this->load->view('ui/admin_home');
        }

更改为:

public function home(){
         $data['cookie'] = $this->input->cookie('rememeber', TRUE);
          $this->load->view('ui/admin_home',$data);
        }

您也可以通过调用它在视图页面中使用它。