Nabin
Nabin

Reputation: 166

Creating Cookies in Codeigniter

Well I have created sessions but having trouble implementing cookies in my website. In config file i have set $config['sess_expire_on_close'] = TRUE; so that user's session expires on closing browser. Now what i want is, On login if user checks remember me ... all data should be stored in a cookie so that on closing browser, user is still logged on.

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;
    }    
}

Does creating cookie automatically creates session? or we have put these data in session manually again?

Upvotes: 3

Views: 6209

Answers (2)

tmarois
tmarois

Reputation: 2470

In CodeIgniter, you can use 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);

Upvotes: 3

Saty
Saty

Reputation: 22532

First of all you need to load cookie helper

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

Set your 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',
);

Just pass your array into set cookie

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

And you can retrieve it using

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

Also read manual

Upvotes: 2

Related Questions