cookies are driving me mad... please help

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
jasongr
Forum Contributor
Posts: 206
Joined: Tue Jul 27, 2004 6:19 am

cookies are driving me mad... please help

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

use .test.com as that will match all subdomains of test.com
jasongr
Forum Contributor
Posts: 206
Joined: Tue Jul 27, 2004 6:19 am

Post 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...
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

yep.
jasongr
Forum Contributor
Posts: 206
Joined: Tue Jul 27, 2004 6:19 am

Post by jasongr »

thank you again
jasongr
Forum Contributor
Posts: 206
Joined: Tue Jul 27, 2004 6:19 am

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

yep:
bool array_key_exists ( mixed key, array search)
;)
jasongr
Forum Contributor
Posts: 206
Joined: Tue Jul 27, 2004 6:19 am

Post by jasongr »

of course
I knew it was a stupid bug
Post Reply