Page 1 of 1

cookies are driving me mad... please help

Posted: Tue Jul 27, 2004 11:49 am
by jasongr
I am trying to send a simple cookie from a PHP code.
Here is my code:

Code: Select all

// should use one of the domains below
$domain = 'www.test.com';
$domain = '.test.com';
$domain = 'test.com';
setcookie('name', $value, time() + 31536000, '/', $domain);
Now, I don't know what is the correct format of the domain section.

no matter which domain format I choose, the cookie gets saved on my computer successfully.

However, sometimes when I try to get the cookie using:

Code: Select all

if (!isset($_COOKIE['name'])) {
  echo 'cookie is missing';
}
else {
  $value = $_COOKIE['name'];
}
I get the error message saying 'cookie is missing'!!!

I am saying sometimes because the behaviour isn't fixed... sometimes it will work and sometimes not...

Help would be appreciated..
thanks

Posted: Tue Jul 27, 2004 11:50 am
by feyd
use .test.com as that will match all subdomains of test.com

Posted: Tue Jul 27, 2004 11:54 am
by jasongr
Thank you

Should there be a special treatment for the IP address of the site?
that is, if a user goes to my site by typing its IP address and not using the domain name, then what format should I use for the cookie?

I am guessing the IP address...

Posted: Tue Jul 27, 2004 11:56 am
by feyd
yep.

Posted: Tue Jul 27, 2004 12:03 pm
by jasongr
thank you again

Posted: Tue Jul 27, 2004 12:11 pm
by jasongr
I have one last strange problem...

this is the code that I use check if the cookie exists:

Code: Select all

$keys = array_keys($_COOKIE);
foreach ($keys as $key) {
  echo "cookie key: " . $key;
}
  	  	
if (array_key_exists($_COOKIE, 'name')) {
  echo "FOUND COOKIE: " . $_COOKIE['name'];
}
else {
  echo "Can't find cookie";
}
Now, despite the fact that the name of the cookie ('name') is displayed in the foreach loop, the if statement fails!!!
why is that?
am I missing something trivial?

thanks

Posted: Tue Jul 27, 2004 12:19 pm
by feyd
yep:
bool array_key_exists ( mixed key, array search)
;)

Posted: Tue Jul 27, 2004 12:54 pm
by jasongr
of course
I knew it was a stupid bug