Setcookie() Path Problems / Gotchas In PHP
April 22nd, 2010 | by admin |
From php.net:“The path on the server in which the cookie will be available on. If set to ‘/’, the cookie will be available within the entire domain. If set to ‘/foo/’, the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in.”
Setting a cookie in PHP using…
setcookie("name", "value", time()+6600);
Will cause you problems when trying to access the cookie using $_COOKIE['cookie-name'] from elsewhere in your site. This is because when you leave out the path parameter in the setcookie() function PHP gives a default path of the directory setcookie() was executed in. If you need to access $_COOKIE from anywhere in your site then make sure you use a “/” as the parameter following the cookies expiry parameter.
This could be a potential major pitfall for many developers who normally use setcookie() with the minimum required parameters!
Here is the correct way to use setcookie() minimally…
setcookie("name", "value", time()+6600, "/");
And as another potential gotcha, make sure you then delete the cookie when you need to by using the same method, otherwise the cookie won’t get deleted by the browser. Correctly delete the cookie using…
setcookie("name","",time() - 3600, "/");
Home
HYGEN Web Design
