Page 1 of 1

set_cookie and display cookie after been created

Posted: Thu Feb 09, 2006 5:01 am
by duk
why i cant do this:

Code: Select all

setcookie("CINTRA", $temp_hash, time()+3600);
echo $_COOKIE['CINTRA'];
Notice: Undefined index: CINTRA .....
then if i refresh its ok...

Posted: Thu Feb 09, 2006 6:41 am
by shiznatix
yes this is standard cookie behavior. the cookie will only be noticed on the next time they goto the page or any other page on your server. what you can do it

Code: Select all

if (empty($_COOKIE['CINTRA']))
{
    setcookie("CINTRA", $temp_hash, time()+3600);
    $_COOKIE['CINTRA'] = $temp_hash;
}

echo $_COOKIE['CINTRA'];
this will make the $_COOKIE['CINTRA'] available to be used as a variable like that anywhere on the page but the cookie won't really be there until a page refresh, you are just kind of faking it until then.

Posted: Thu Feb 09, 2006 7:41 am
by raghavan20
you are right shiznatix, the cookie is not available until a page refresh happens. But I am thinking why is it happening, is it because it takes more time to create a cookie and by the time you read the next line to access cookie it is not created or being created.... :roll:

Posted: Thu Feb 09, 2006 8:36 am
by duk
thanks for that idea, didn't thought in that...

i think the same maybe is the time that takes to create the cookie...

Posted: Thu Feb 09, 2006 10:09 am
by Jenk
cookies are stored client-side, not server side. Thus the page request has to complete, so the output headers can be sent to the client (cookies are set as part of the headers, iirc)

the $_COOKIE super global is formed and defined from the page request sent by the user agent. Because of this, this means the $_COOKIE super global is defined before anything else happens in your PHP script. So setcookie() has no bearing on it until the next page request.