Forum Moderators: coopster

Message Too Old, No Replies

Php Cookie Problem

         

Dragosh

10:51 am on Aug 20, 2007 (gmt 0)

10+ Year Member



I've read that cookie must be set before any output,even before <html> and <head> tag. So i did. But when i access the first time the page i get error messages and notices that "category" (name of cookie) index does not exist. Howether when accessing same page the second time everything works ok.

Habtom

10:56 am on Aug 20, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



That is how it is. You can't set a cookie the first time and begin reading it immediately, but the cookies can be read when the page is reloaded.

Habtom

dmorison

11:00 am on Aug 20, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi,

When you set a cookie with setcookie(), the corresponding $_COOKIE["name"] is not available within that instance of the script because all it has done is set the headers. $_COOKIE only contains cookies that were sent with the page request, which is why it is empty the first time through but there on the next page view.

It sounds like you want to be doing something like this instead:

if ($_COOKIE["someVariable"])
{
$someVariable = $_COOKIE["someVariable"];
}
else
{
$someVariable = "Default Value"
}

setcookie("someVariable",$someVariable);

...This way, you only access $_COOKIE[] once at the top of your script, and then use $someVariable throughout the rest of your code...