在Codeigniter中创建cookie


Creating Cookies in Codeigniter

我已经创建了会话,但在我的网站上实现cookie有困难。在配置文件中,我已经设置了$config['sess_expire_on_close'] = TRUE;,以便用户的会话在关闭浏览器时过期。现在我想要的是,登录时如果用户检查记住我…所有数据都应该存储在一个cookie中,以便在关闭浏览器时,用户仍然登录。

function login($email, $password, $loginas) {
    if ($loginas == 'user') {
        $this->db->select('*');
        $this->db->where('email', $email);
        $this->db->where('password', $password);
        $query = $this->db->get("user_info");
        if ($query->num_rows() > 0) {
            foreach ($query->result() as $rows) {
                $newdata = array('id' => $rows->id,
                    'firstname' => $rows->firstname,
                    'lastname' => $rows->lastname,
                    'address' => $rows->address,
                    'city' => $rows->city,
                    'email' => $rows->email,
                    'phone' => $rows->phone,
                    'logged_in' => TRUE,
                );
            }
            $this->session->set_userdata($newdata);
            if ($rememberme == 'on') {
                // create a cookie here with all data that i have put in session                                                  
            }
            return TRUE;
        }
        return FALSE;
    }    
}

创建cookie是否自动创建会话?还是我们再次手动将这些数据放入session ?

在CodeIgniter中,您可以使用set_cookie()

$cookie = array(
    'name'   => 'The Cookie Name',
    'value'  => 'The Value',
    'expire' => '86500',
    'domain' => '.example.com',
    'path'   => '/',
    'prefix' => 'myprefix_',
    'secure' => TRUE
);
$this->input->set_cookie($cookie);

首先你需要加载cookie helper

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

设置你的cookie

    $cookie = array(
    'name'   => "cookieName",
    'value'  => array('id'=>$rows->id,
    'firstname'=>$rows->firstname,
    'lastname'=>$rows->lastname,
    'address'=>$rows->address,
    'city'=>$rows->city,
    'email'=>$rows->email,
    'phone'=>$rows->phone,
    'logged_in'=>TRUE
        ) ,
'expire' => '86500',
);

将数组传入set cookie

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

可以使用

检索
$cookie['cookieName']['id'];

同时阅读手册