Wednesday, February 09, 2005

ColdFusion: cfcookie

Question: I would like to delete a specific cookie and not just set its value to nothing but delete it entirely from the client browser.

cfcookie name="TheCookie" value="" expires="NOW" doesn't seem to want to work.

Answer: The problem you're running into is that cookies are identified by more than their name. In order to change or override a cookie you'll need to set a new cookie with the same exact identifier.

A cookie is uniquely identified by:
- name
- domain
- path
- security requirement

Normally, this means setting the name and path, since the application is rarely going to need to set something other than the default for domain or secure. The default path of a cookie set without a path=value is the same as the resource that set it (the page). You should be aware of this if you set cookies using cfheader.

However, if you are setting things with cfcookie, then things are both easier and more complex. Setting no path value in cfcookie is equivalent to setting path=/ in the set-cookie header. *But* cfcookie won't allow you to set a path unless you also set a domain; domains need at least 2 dots for three-letter top level domains, and at least 3 dots for two-letter top level domains. The CF docs say the cookie domain must start with a dot, but that's wrong (CF may requiere it, but cookies don't). So consider the following:

1. cfcookie name="foo" value="bar"/
2. cfcookie name="foo" value="bar" path="/foodir/"/
3. cfcookie name="foo" value="bar" path="/foodir/" domain=""/
4. cfcookie name="foo" value="bar" path="/foodir/" domain=""/
5. cfcookie name="foo" value="bar" path="/foodir/" domain=""/

1 and 4 are valid. 5 is not. CF may prevent you from using 2 or 3.

Crazy, huh? What's even crazier is that if you set *both* 1 and 4, then every page under foodir has *two* cookies with the same name that the browser can choose from, and if you delete one -- the other is still there, with the same name, making it look like you didn't delete anything.

When testing if you can delete cookies, make sure you clear your browser of all the old stuff first. The reason is that if you set a bad cookie while testing, you cannot delete it without setting another one exactly the same way. And you will run in circles because of the two-cookie thing.


Post a Comment

<< Home