From the department of "Code I will write once and forget about in a day" comes the setCookie UDF. Inspired by a question on Stack Overflow (how to set expiration date on a cookie in cfscript), the UDF allows you to set cookies in cfscript that have expiration dates. You can actually pass all the arguments if you want, like domain, httpOnly (CF9), etc. Here is the UDF:
<cfcookie attributecollection="#args#">
</cffunction>
<cffunction name="setCookie" access="public" returnType="void" output="false">
<cfargument name="name" type="string" required="true">
<cfargument name="value" type="string" required="false">
<cfargument name="expires" type="any" required="false">
<cfargument name="domain" type="string" required="false">
<cfargument name="httpOnly" type="boolean" required="false">
<cfargument name="path" type="string" required="false">
<cfargument name="secure" type="boolean" required="false">
<cfset var args = {}>
<cfset var arg = "">
<cfloop item="arg" collection="#arguments#">
<cfif not isNull(arguments[arg])>
<cfset args[arg] = arguments[arg]>
</cfif>
</cfloop>
And a few examples - although the first two calls are a bit silly - you wouldn't need the UDF for them:
<cfdump var="#cookie#">
<cfscript>
if(!structKeyExists(cookie, "hitcount")) setCookie("hitcount",0);
setCookie("hitcount", ++cookie.hitcount);
setCookie("foreverknight",createUUID(),"never");
</cfscript>
Two small notes: First, if I were to add support to this in ColdFusion, I'd make it much easier. Just simply allow structs as values for cookies: cookie.booger = { value="something", expires="never"}. ColdFusion should be smart enough to translate that. Secondly - I noticed today that when a cookie is set to never, it gets set to a date in 2040. Anyone else realize that that date isn't that far away? Shoot - it's only a few days after HTML5 will be done. (I kid!)
Archived Comments
The date being in 2040 is because that's 30 years from the current date. There was a flame-war inducing scandal about that ("omg cold fusion stores your information for 30 years!!!1") seemingly forever ago. I'd have thought that an old codger like yourself would have remembered that one. ;)
Oh god that _does_ sound familiar.
It's cool to see that this syntax is working these days:
isNull(arguments[arg])
... with the public CF9 beta, that would have thrown an error if arg did not exist in arguments. Very sweeet.
Thanks Ray. Just what I need. Yes, I know. My client is still using CF9. Doh...