JelleP
JelleP

Reputation: 1004

Cannot get Cookie

Until now i always worked with session in Codeigniter. But now there is to much data for an session. I like to use cookies, but it doesn,t work for me.

When i try this simple example, the cookie is alsoempty.

$cookie = array(
'name'   => 'some_value',
'value'  => 'The Value'
);
set_cookie($cookie);
var_dump(get_cookie('some_value'));
die();

Whats wrong?

Thanks for your help!!

Upvotes: 0

Views: 218

Answers (3)

dmayo
dmayo

Reputation: 640

Cookies cannot hold arrays, just plain text. @RageZ had a good clue with the for loop which would set many cookies (as many as vars in array). @Damien suggests "serialized" and another option would be to jSon the array into a str with native php function "json_encode()"

Upvotes: 0

Damien Pirsy
Damien Pirsy

Reputation: 25435

  1. You should set an expiration value, i.e. seconds from the moment it gets created to when it will expire.
  2. the "name" value must be a string, not an array. If you want multiple infos, you can just serialize() the array.

Example code:

$cookie = array(
    'name'   => 'users_new',
    'value'  => serialize($users_new),
    'expire' => '86500'
);

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

You don't need to load the cookie helper if you just use the input class. No problem, I know, just to avoid useless lines of code :)

Upvotes: 0

RageZ
RageZ

Reputation: 27313

Cookies are sent by the browser so you would have to wait the user reload a page.

So the basic process is:

  1. you set a cookie
  2. the user resend the cookie on the next request
  3. you can access the cookie value using get_cookie

EDIT:

setcookie is used this way, it won't work with an array

setcookie("TestCookie", $value);
setcookie("TestCookie", $value, time()+3600);  /* expire dans 1 heure */
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", "example.com", 1);

so you should do:

foreach ($cookie as $key => $val) {
   setcookie($key, $val);
}

Upvotes: 1

Related Questions