set_cookie and display cookie after been created

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
duk
Forum Contributor
Posts: 199
Joined: Wed May 19, 2004 8:45 am
Location: London

set_cookie and display cookie after been created

Post 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...
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post 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.
User avatar
raghavan20
DevNet Resident
Posts: 1451
Joined: Sat Jun 11, 2005 6:57 am
Location: London, UK
Contact:

Post 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:
duk
Forum Contributor
Posts: 199
Joined: Wed May 19, 2004 8:45 am
Location: London

Post 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...
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post 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.
Post Reply