note 35924 deleted from function.setcookie by tularis
| From: | tularis@php.net | Date: | Sun, 02 Jan 2005 14:24:54 +0000 |
| Subject: | note 35924 deleted from function.setcookie by tularis | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-82593@lists.php.net to get a copy of this message | ||
Note Submitter: george at whiffen dot net
----
WARNING: You probably do NOT want the default setting for cookie path!
TIP: Explicitly set cookie's path to "/" unless you are ready for unexpected results
i.e.
Use this: setcookie('mycookie','myvalue',0,'/')
Not this: setcookie('mycookie','myvalue')
EXPLANATION: Browsers will store separate cookies for different path settings and you may not get
the one you want/expect. In particular, you may think you have deleted a cookie only to find that
your script is still being sent a cookie with the same name but a different path.
If you don't specify a path the browser will create different cookies depending on what
directory your script runs in. Move your script and you get a new cookie. Delete the new cookie
and the old one is still there.
To make it worse, you can also have different values for the same path if you used different
syntaxes i.e. with/without a trailing slash e.g.
setcookie('mycookie','myvalue',0,'/subdir')
setcookie('mycookie','myvalue',0,'/subdir/')
These are two different cookies, which can have different values. Deleting or changing one has no
effect on the other.
Similarily, from a top level script, these are two different cookies:
setcookie('mycookie','myvalue')
setcookie('mycookie','myvalue',0,'/')
That means if you just have a plain path-less setcookie() in a top level script which you then move
to a sub-directory, you will get two different cookies. The original top-level one is then hard to
get rid of:
You cannot use: setcookie('mycookie','myvalue')
This will create a new cookie with path set to the sub-directory path
Nor can you use: setcookie('mycookie','myvalue',0,'/')
This will create a new cookie with path set to '/', not to blank
Nor can you use: setcookie('mycookie','myvalue',0,'')
This will be treated as an alternate syntax for setcookie('mycookie','myvalue')
You must use: setcookie('mycookie','myvalue',0,' ') // path set to
space
This will change a cookie set in a top-level script with no path.
It's not just a matter of cookies hanging about when you thought you deleted them, the value
you will get when the same cookie is set with different paths seems to be just the last one set, not
the most specific one.
Sorry if I'm not explaining this well, but that's the point! Unless you
"hard-code" your cookie path to /, you are very likely to get complications sooner or
later ;). If, as I was, you are trying to change a top-level insecure cookie to a sub-directory
secure cookie, it's a nightmare to work out what's going on and whether or not you've
got rid of any old insecure cookies.