Get cookie metadata in ColdFusion

EDIT: Unfortunately, I was wrong about this! Please see Jason’s comment below.

As you know, ColdFusion makes it pretty easy to get cookies sent to the page in the current request. All cookies are stored in a simple structure that you can either dump or simply loop over.

<cfloop item="c" collection="#cookie#"> <cfoutput>cookie[#c#] = #cookie[c]#<br/></cfoutput> </cfloop>

But while this gives you the name and value of all cookies, it doesn't tell you anything else about the cookie, like it's expiration, path, or other values. For that, you have to get into the request at the Java level. Luckily, ColdFusion makes this simple too:

<cfset cookies = getPageContext().getRequest().getCookies()>

Where did this line of code come from? getPageContext() is a CFML function that returns the underlying Java PageContext object. From some Googling, I found that I could get the Request data from that Page object and then get an array of cookies using getCookies. Pretty simple, right? Each cookie object has all it's values available via simple get methods. You can see the documentation for that here. Here is a trivial sample that just loops over them and prints out some of the values.

<cfset cookies = getPageContext().getRequest().getCookies()> <cfloop index="c" array="#cookies#"> <cfoutput> Name=#c.getName()#<br/> Value=#c.getValue()#<br/> Path=#c.getPath()#<br/> Domain=#c.getDomain()#<br/> MaxAge=#c.getMaxAge()#<br/> <p> </cfoutput> <cfdump var="#c#"> </cfloop>

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.

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

Comments