Wednesday, 17 June 2009

PHP setcookie overwriting problem.

I've just found a tiny error in how I've been taught to create cookies in PHP. So thought i'd share it incase it was driving anyone else crazy too.

Symptoms: cookie data is overwritten or not passed properly.

Solution: Firstly lets make sure you're writing cookie's properly.. (time is set to 30days)
 setcookie('name', 'value', time() + 3600*24*30);

It's likely this php may sit in a header file or a page template so to make sure this cookie isn't overwritten if it appears elsewhere in the site write it like this..
 if(!isset($_COOKIE['name']))
{
  setcookie('name', 'value', time() + 3600*24*30);

}

Now this is where i started having strange results, basically if the cookie is initially written on a second level page eg. hilikusOnline.co.uk/podcasts/theshow then it could be overwritten or unavailable on a root level such as hilikusOnline.co.uk/home

to make sure the cookie is set at root level, you must include "/" as a cookie variable. So the correct code now looks like this:
  if(!isset($_COOKIE['name']))
{
  setcookie('name', 'value', time() + 3600*24*30, "/");

}

That's it!

No comments:

Post a Comment