Working with Cookies
From WikiPedia: A cookie, also known as a web cookie, browser cookie, and HTTP cookie, is a piece of text stored by a user's web browser. A cookie can be used for authentication, storing site preferences, shopping cart contents, the identifier for a server-based session, or anything else that can be accomplished through storing text data. A cookie consists of one or more name-value pairs containing bits of information, which may be encrypted for information privacy and data security purposes. The cookie is sent as an HTTP header by a web server to a web browser and then sent back unchanged by the browser each time it accesses that server.
Reading and writing cookies within a CFML application couldn't be easier. Through either the base language, a tag or a function, you have access to the cookie functionality quickly and easily.
Reading HTTP Cookie's
Any cookies sent to the server by the browser can easily be read using the cookie scope. This is a standard CFML structure that holds all the values of the incoming cookies.
<cfdump var="#cookie#"> <cfif StructKeyExists( cookie, "mycookie" )> <cfoutput>#cookie.mycookie#</cfoutput> </cfif>
Creating/Setting HTTP Cookies
Creating a new HTTP cookie is just as easy as reading them. You can set a minimal cookie by simply setting a value to the cookie structure.
<cfset cookie.mycookie = "This is a value">
CFML doesn't stop there though when it comes to controlling the properties of an outgoing HTTP cookie. Using either the CFCOOKIE or the SetCookie() function you can control all aspects of the HTTP cookie. From properties such as the domain, path and security settings, these can be controlled on an individual basis.
<!--- Using the tag to set a cookie ---> <cfcookie name="mycookie" value="This is a value" expires="60" httponly="true"> <!--- Using the function to set a cookie ---> <cfset SetCookie( name="mycookie", value="This is a value", expires="60", httponly="true" )>
A cookie can be set anywhere in your CFML application. However, if your request has already been flushed, or any content sent to the client, then the cookie will fail to set.
Deleting HTTP Cookies
By default, if you do not specify any expires attribute the cookie will be deleted as soon as the user closes their browser window. If you wish to delete the cookie immediately then you can use the EXPIRES="NOW" directive.
<!--- Using the tag to set a cookie ---> <cfcookie name="mycookie" expires="now"> <!--- Using the function to set a cookie ---> <cfset SetCookie( name="mycookie", expires="now" )>
This will direct the browser to delete the cookie from the browser.
CFML Engine Cookies