Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't cookie work in CodeIgniter?

I use this function to add cookie and it adds perfectly as I can see in browser options.

function login($username,$password){

    $cookieUsername = array(
        'name'   => 'user',
        'value'  => md5($username),
        'expire' => time()+1000,
        'path'   => '/',
        'secure' => TRUE
    );

    $cookiePassword = array(
        'name'   => 'pass',
        'value'  => $password,
        'expire' => time()+1000,
        'path'   => '/',
        'secure' => TRUE
    );

    $this->input->set_cookie($cookieUsername);
    $this->input->set_cookie($cookiePassword);

}

I am unable to get back the cookie from this function:

 echo $this->input->cookie('user');

Please help - how can I get cookie back from CodeIgniter?

like image 630
danny Avatar asked Nov 28 '22 06:11

danny


2 Answers

Its problem with CI built in function which writes the cookie. What i changed is now i am setting cookie whith

setcookie($name,$value,$expire,$path); 

function and getting it back through

$this->input->cookie('user',TRUE); 

this is work damn fine!

like image 110
danny Avatar answered Dec 06 '22 01:12

danny


You can not get cookie on the same http request. Once you set a cookie it must be sent to browser by Set-Cookie header. And you can not send header until the http transaction is completed. After that browser will get the cookie and on the next request browser will send it to server by Cookie header.

From PHP.NET

Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter.

So the cookie will be available on the next page load.

like image 29
Shiplu Mokaddim Avatar answered Dec 06 '22 01:12

Shiplu Mokaddim