Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

setCookie needs refresh to get value?

Status
Not open for further replies.

styleBunny

Technical User
Jun 20, 2002
133
0
0
AU
Hi peeps,

I am using setCookie() to create a simple cookie. Then i use a simple if statement to test that the cookie has been created.

When load the page, it tells me the cookie has not been set, only when i hit refresh it will the of the existance of the cookie be recognised.

I have tried putting the setCookie code above the <html> start tag and then the code to test in the body but this wont work first time round either.

Is this possibly a server issue even?

thanks
Paul.
 
no, it works that way

Bastien

Cat, the other other white meat
 
Hi Bastien,

Thanks for the reply. So cookies can only be set the first time the page is loaded, and not read its value?

Seems odd, as when i refresh the page, in theory it sets the same cookie again, but this time the if statement can see its value. :|

Cheers
Paul.
 
its because....
When you run the php script that creates the cookie and then tests for its existence, it is running on the server machine. It's not until the HTML generated by the script gets to your browser that the cookie actually gets created.
Just one of the fun ways the web programming model works
 
if you've just created the cookie, you should know what is in it anyway I would think. Just test for the existence of the cookie ($_COOKIE[]) and away you go
 
I try another way of wording it too...

This is because the cookie information coming from the client is sent as part of the HTML request itself, therefore, the first time your page is loaded, the client has no information, and sends none in the HTML request... hence, your info is blank.

It's the same reason you need two page loads to see if a client accepts cookies or not.

All that said, the work around is to use code of this sort (mind you that this will cause some confusion if the client has cookies turned off)

Code:
function setCookiesMyWay($key, $value, $expire)
{
  setcookie($name, $value, $expire);
  $_COOKIE[$name] = $value;
}

Obviouslly you can easily robustify it to handle all the cookie parameters you're interested in.... but this lets you leave all your code in place and make the cookie values available early.
 
Hi guys,

Some good explanations and work arounds there, plenny to digest for this cookie newb.

Thanks yall.
Paul.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top