【问题标题】:Creating Cookies in Codeigniter在 Codeigniter 中创建 Cookie
【发布时间】:2015-09-10 06:26:50
【问题描述】:

好吧,我已经创建了会话,但是在我的网站中实现 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 会自动创建会话吗?还是我们再次手动将这些数据放入会话中?

【问题讨论】:

    标签: php codeigniter session cookies


    【解决方案1】:

    在 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);
    

    【讨论】:

    • 我删除了“.” (点)域名。这对我有用。
    【解决方案2】:

    首先你需要加载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',
    );
    

    只需将您的数组传递到设置的 cookie 中

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

    你可以使用它来检索它

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

    另请阅读manual

    【讨论】:

    • 我如何在我的网站开始时检查我的 cookie 中是否有值,...在我关闭浏览器后我是否必须将这些值放入会话中,因为会话中的数据会到时候就走了
    • 您可以查看if($this->input->cookie('cookiename')!=''){ //exists }。我认为这里不需要使用 cookie,因为您已经在会话中保存了数据!!!
    • 我需要使用 cookie,因为如果我关闭浏览器,会话中的数据就会过期。所以如果用户检查了记住我,他仍然必须登录。我认为上面设置 cookie 的代码不起作用,因为回显 $this->input->cookie('id') 没有显示任何内容
    猜你喜欢
    • 2012-01-03
    • 2017-05-20
    • 1970-01-01
    • 2015-02-22
    • 2023-04-11
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多