Reputation: 435
Cookies arent being set in my first view.
Is this how it should be ? or am I mistaken
Please view the code below for further illustration:
if( !get_cookie('rate') ){
$cookie_rate = array(
'name' => 'rate',
'value' => '10',
'expire' => '100000'
);
set_cookie($cookie_rate);
}
var_dump( get_cookie('rate') ); //returns ( boolean false )
if( !isset($_COOKIE['foo']) ){
$_COOKIE['foo'] = 'bar';
}
var_dump( $_COOKIE['foo'] ); // This yields string 'bar' (length=3) on the first visit
Doing the same thing with php cookies yeilds an array with cookie values.
Upvotes: 0
Views: 4738
Reputation: 100195
Thats probably not the problem, in fact thats how cookie works, its set and on next page load it seems to be visible from then.
Upvotes: 1
Reputation: 31641
This isn't a CodeIgniter vs PHP issue. You just don't understand how cookies work.
Cookies are a header sent by the server which the browser must send back on subsequent requests. $this->input->set_cookie()
and set_cookie()
send a cookie header.
$_COOKIES
on PHP (and thus $this->input->cookie()
and therefore the get_cookie()
helper) only contain cookies which the browser sent.
Thus when you set a cookie with set_cookie()
, you won't be able to get_cookie()
until the browser's next request.
Upvotes: 3
Reputation: 3908
If I understood this right youre trying to see the data of the cookie before reloading the page which won't work. Try setting the cookie, reloading the page and then checking the cookie for data.
Also sometimes you need to specify domain and such, perhaps it doesn't apply right now but it might be nice to know later if they suddenly stop working, from CI-documentation:
$cookie = array(
'name' => 'The Cookie Name',
'value' => 'The Value',
'expire' => '86500',
'domain' => '.some-domain.com',
'path' => '/',
'prefix' => 'myprefix_',
'secure' => TRUE
);
$this->input->set_cookie($cookie);
Also, consider using the session class instead of cookies if you don't need anything specifically from cookies since they are more secure. http://codeigniter.com/user_guide/libraries/sessions.html
Upvotes: 1
Reputation: 449783
Seeing as CI's set_cookie
probably utilizes the same mechanism as PHP's setcookie()
, this entry from the manual probably applies:
Common pitfalls
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. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.
I can't see any mention of this behaviour in the CI manual, but it's likely to be the same thing.
Upvotes: 2