|
Cookies in ColdFusion - cfcookie or cfset? |
ColdFusion can create, edit and delete cookies quite easily, but what are the functional differences in how you create them? Is one way better than another?
I had previously written some cookie based functionality to remember where a user was when they logged (or timed) out of an application. This meant that when they logged back in they could be redirected to where they were, rather than just dumped on the homepage.
This worked very well until I started rolling out multiple instances of this application. The problem then is that using this way of setting the cookie does not allow you to set any of the other cookie properties, and it only last for THAT browser session, so it's not very long lived. Also without setting the domain and path for the cookie my application was picking cookies created in other instances of the app. A kind of cookie scope bleed through.
You can set cookie values much like any other ColdFusion variable statement:
This routine was called on every page load, so I am simply overwriting the same cookie value on each page request.
Writing the cookie to the client browser like this does not allow you to set any other of the cookies properties, such as the domain, path and expiry (Adobe docs link: http://www.adobe.com/livedocs/coldfusion/6.1/htmldocs/tags-a18.htm
Using the cfcookie tag you can easily create these:
2<cfset request.cookiePath = listFirst(cgi.script_name,'/')>
3<cfset request.cookiePath = '/' & request.cookiePath & '/'>
4
5<cfcookie name="requestedTemplate" value="#request.cookieValue#"
6expires="never"
7domain="#cgi.server_name#"
8path="#request.cookiePath#">
In this way you can fully control which domain, and even which site a cookie belongs to. This sends the client a much more strict cookie value.
I'm almost surprised that you cannot address the cookie as a struct.
http://kb2.adobe.com/cps/181/tn_18100.html