Settings cookies (with expiration, etc) in CFScript

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:

<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> <cfcookie attributecollection="#args#"> </cffunction>

And a few examples - although the first two calls are a bit silly - you wouldn't need the UDF for them:

<cfscript> if(!structKeyExists(cookie, "hitcount")) setCookie("hitcount",0); setCookie("hitcount", ++cookie.hitcount); setCookie("foreverknight",createUUID(),"never"); </cfscript> <cfdump var="#cookie#">

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!)

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Comments