- CFML Reference User Guide
- ColdFusion functions
- ColdFusion functions by category
- Functions a-b
- Abs
- ACos
- AddSOAPRequestHeader
- AddSOAPResponseHeader
- AjaxLink
- AjaxOnLoad
- ApplicationStop
- ArrayAppend
- ArrayAvg
- ArrayClear
- ArrayContains
- ArrayContainsNoCase
- ArrayDelete
- ArrayDeleteAt
- ArrayDeleteNoCase
- ArrayEach
- ArrayFilter
- ArrayFind
- ArrayFindAll
- ArrayFindAllNoCase
- ArrayFindNoCase
- ArrayInsertAt
- ArrayIsDefined
- ArrayIsEmpty
- ArrayLen
- ArrayMap
- ArrayMax
- ArrayMin
- ArrayNew
- ArrayPrepend
- ArrayReduce
- ArrayResize
- ArraySet
- ArraySetMetadata
- ArraySlice
- ArraySort
- ArraySum
- ArraySwap
- ArrayToList
- Asc
- ASin
- Atn
- AuthenticatedContext
- AuthenticatedUser
- BinaryDecode
- BinaryEncode
- BitAnd
- BitMaskClear
- BitMaskRead
- BitMaskSet
- BitNot
- BitOr
- BitSHLN
- BitSHRN
- BitXor
- BooleanFormat
- Abs
- Functions-c-d
- CacheGet
- CacheGetAllIds
- CacheGetMetadata
- CacheGetProperties
- CacheGetSession
- CacheIdExists
- CachePut
- CacheRegionExists
- CacheRegionNew
- CacheRegionRemove
- CacheRemove
- CacheRemoveAll
- CacheSetProperties
- CallStackDump
- CallStackGet
- CanDeSerialize
- Canonicalize
- CanSerialize
- Ceiling
- CharsetDecode
- CharsetEncode
- Chr
- CJustify
- Compare
- CompareNoCase
- Cos
- CreateDate
- CreateDateTime
- CreateObject
- CreateObject: .NET object
- CreateObject: COM object
- CreateObject: component object
- CreateObject: CORBA object
- CreateObject: Java or EJB object
- CreateObject: web service object
- CreateODBCDate
- CreateODBCDateTime
- CreateODBCTime
- CreateSignedJWT
- CreateEncryptedJWT
- CreateTime
- CreateTimeSpan
- CreateUUID
- CSRFGenerateToken
- CSRFVerifyToken
- CSVRead
- CSVWrite
- CSVProcess
- DateAdd
- DateCompare
- DateConvert
- DateDiff
- DateFormat
- DatePart
- DateTimeFormat
- Day
- DayOfWeek
- DayOfWeekAsString
- DayOfYear
- DaysInMonth
- DaysInYear
- DE
- DecimalFormat
- DecodeForHTML
- DecodeFromURL
- DecrementValue
- Decrypt
- DecryptBinary
- DeleteClientVariable
- Deserialize
- DeserializeJSON
- DeserializeXML
- DirectoryCopy
- DirectoryCreate
- DirectoryDelete
- DirectoryExists
- DirectoryList
- DirectoryRename
- DollarFormat
- DotNetToCFType
- Duplicate
- Functions-e-g
- EncodeForCSS
- EncodeForDN
- EncodeForHTML
- EncodeForHTMLAttribute
- EncodeForJavaScript
- EncodeForLDAP
- EncodeForURL
- EncodeForXML
- EncodeForXMLAttribute
- EncodeForXpath
- Encrypt
- EncryptBinary
- EntityDelete
- EntityLoad
- EntityLoadByExample
- EntityLoadByPK
- EntityMerge
- EntityNew
- EntityReload
- EntitySave
- EntityToQuery
- Evaluate
- Exp
- ExpandPath
- FileClose
- FileCopy
- FileDelete
- FileExists
- FileGetMimeType
- FileIsEOF
- FileMove
- FileOpen
- FileRead
- FileReadBinary
- FileReadLine
- FileSeek
- FileSetAccessMode
- FileSetAttribute
- FileSetLastModified
- FileSkipBytes
- FileUpload
- FileUploadAll
- FileWrite
- FileWriteLine
- Find
- FindNoCase
- FindOneOf
- FirstDayOfMonth
- Fix
- Floor
- FormatBaseN
- GeneratePBKDFKey
- GenerateSecretKey
- GetApplicationMetadata
- GetAuthUser
- GetBaseTagData
- GetBaseTagList
- GetBaseTemplatePath
- GetClientVariablesList
- GetComponentMetaData
- GetContextRoot
- GetCPUUsage
- GetCurrentTemplatePath
- GetCSPNonce
- GetDirectoryFromPath
- GetEncoding
- GetException
- GetFileFromPath
- GetFileInfo
- GetFreeSpace
- GetFunctionCalledName
- GetFunctionList
- GetGatewayHelper
- GetHttpRequestData
- GetHttpTimeString
- GetK2ServerDocCount
- GetK2ServerDocCountLimit
- GetLocale
- GetLocaleDisplayName
- GetLocalHostIP
- GetMetaData
- GetMetricData
- GetPageContext
- GetPropertyString
- GetPropertyFile
- GetPrinterInfo
- GetPrinterList
- GetProfileSections
- GetProfileString
- GetReadableImageFormats
- GetSafeHTML
- GetSAMLAuthRequest
- GetSAMLLogoutRequest
- Generate3DesKey
- GenerateSAMLSPMetadata
- GetSOAPRequest
- GetSOAPRequestHeader
- GetSOAPResponse
- GetSOAPResponseHeader
- GetSystemFreeMemory
- GetSystemTotalMemory
- GetTempDirectory
- GetTempFile
- GetTemplatePath
- GetTickCount
- GetTimeZoneInfo
- GetToken
- GetTotalSpace
- GetUserRoles
- GetVFSMetaData
- GetWriteableImageFormats
- Functions-h-im
- Hash
- HMac
- Hour
- HQLMethods
- HTMLCodeFormat
- HTMLEditFormat
- IIf
- ImageAddBorder
- ImageBlur
- ImageClearRect
- ImageCopy
- ImageCreateCaptcha
- ImageCrop
- ImageDrawArc
- ImageDrawBeveledRect
- ImageDrawCubicCurve
- ImageDrawLine
- ImageDrawLines
- ImageDrawOval
- ImageDrawPoint
- ImageDrawQuadraticCurve
- ImageDrawRect
- ImageDrawRoundRect
- ImageDrawText
- ImageFlip
- ImageGetBlob
- ImageGetBufferedImage
- ImageGetEXIFMetadata
- ImageGetEXIFTag
- ImageGetHeight
- ImageGetIPTCMetadata
- ImageGetIPTCTag
- ImageGetMetadata
- ImageGetWidth
- ImageGrayscale
- ImageInfo
- ImageMakeColorTransparent
- ImageMakeTranslucent
- ImageNegative
- ImageNew
- ImageOverlay
- ImagePaste
- ImageRead
- ImageReadBase64
- ImageResize
- ImageRotate
- ImageRotateDrawingAxis
- ImageScaleToFit
- ImageSetAntialiasing
- ImageSetBackgroundColor
- ImageSetDrawingColor
- ImageSetDrawingStroke
- ImageSetDrawingTransparency
- ImageSharpen
- ImageShear
- ImageShearDrawingAxis
- ImageTranslate
- ImageTranslateDrawingAxis
- ImageWrite
- ImageWriteBase64
- ImageXORDrawingMode
- Functions-in-k
- IncrementValue
- InputBaseN
- Insert
- Int
- InterruptThread
- InvalidateOauthAccesstoken
- Invoke
- InitSAMLAuthRequest
- InitSAMLLogoutRequest
- InvokeCFClientFunction
- IsArray
- IsAuthenticated
- IsAuthorized
- IsBinary
- IsBoolean
- IsClosure
- IsCustomFunction
- IsDate
- IsDateObject
- IsDDX
- IsDebugMode
- IsDefined
- IsImage
- IsImageFile
- IsInstanceOf
- IsIPv6
- IsJSON
- IsK2ServerABroker
- IsK2ServerDocCountExceeded
- IsK2ServerOnline
- IsLeapYear
- IsLocalHost
- IsNull
- IsNumeric
- IsNumericDate
- IsObject
- isOnline
- IsPDFArchive
- IsPDFFile
- IsPDFObject
- IsProtected
- IsQuery
- isSamlLogoutResponse
- isSafeHTML
- IsSimpleValue
- IsSOAPRequest
- IsSpreadsheetFile
- IsSpreadsheetObject
- IsStruct
- isThreadInterrupted
- IsUserInAnyRole
- IsUserInRole
- IsUserLoggedIn
- IsValid
- IsValidOauthAccesstoken
- IsWDDX
- IsXML
- IsXmlAttribute
- IsXmlDoc
- IsXmlElem
- IsXmlNode
- IsXmlRoot
- JavaCast
- JSStringFormat
- Functions-l
- LCase
- Left
- Len
- ListAppend
- ListChangeDelims
- ListContains
- ListContainsNoCase
- ListDeleteAt
- ListEach
- ListFilter
- ListFind
- ListFindNoCase
- ListFirst
- ListGetAt
- ListGetDuplicates
- ListInsertAt
- ListLast
- ListLen
- ListMap
- ListPrepend
- ListQualify
- ListReduce
- ListRemoveDuplicates
- ListRest
- ListSetAt
- ListSort
- ListToArray
- ListValueCount
- ListValueCountNoCase
- LJustify
- Location
- Log
- Log10
- LSCurrencyFormat
- LSDateFormat
- LSDateTimeFormat
- LSEuroCurrencyFormat
- LSIsCurrency
- LSIsDate
- LSIsNumeric
- LSNumberFormat
- LSParseCurrency
- LSParseDateTime
- LSParseEuroCurrency
- LSParseNumber
- LSTimeFormat
- LTrim
- Functions-m-r
- Max
- Mid
- Min
- Minute
- Month
- MonthAsString
- Now
- NumberFormat
- ObjectEquals
- ObjectLoad
- ObjectSave
- OnWSAuthenticate
- ORMClearSession
- ORMCloseAllSessions
- ORMCloseSession
- ORMEvictCollection
- ORMEvictEntity
- ORMEvictQueries
- ORMExecuteQuery
- ORMFlush
- ORMFlushall
- ORMGetSession
- ORMGetSessionFactory
- ORMIndex
- ORMIndexPurge
- ORMReload
- ORMSearch
- ORMSearchOffline
- ParagraphFormat
- ParameterExists
- ParseDateTime
- Pi
- PrecisionEvaluate
- ProcessSAMLResponse
- ProcessSAMLLogoutRequest
- Quarter
- PreserveSingleQuotes
- QueryAddColumn
- QueryAddRow
- QueryConvertForGrid
- QueryExecute
- QueryFilter
- QueryGetResult
- QueryGetRow
- QueryKeyExists
- QueryMap
- QueryNew
- QueryReduce
- QuerySetCell
- QuotedValueList
- QueryEach
- Rand
- Randomize
- RandRange
- ReEscape
- REFind
- REFindNoCase
- ReleaseComObject
- REMatch
- REMatchNoCase
- RemoveCachedQuery
- RemoveChars
- RepeatString
- Replace
- ReplaceList
- ReplaceNoCase
- REReplace
- REReplaceNoCase
- RestDeleteApplication
- RestSetResponse
- RestInitApplication
- Reverse
- Right
- RJustify
- Round
- RTrim
- Functions-s
- Second
- SendGatewayMessage
- SendSAMLLogoutResponse
- Serialize
- SerializeJSON
- SerializeXML
- SessionInvalidate
- SessionRotate
- SessionGetMetaData
- SessionInvalidate
- SessionRotate
- SetDay
- SetEncoding
- SetHour
- SetLocale
- SetMonth
- SetProfileString
- SetPropertyString
- SetVariable
- SetYear
- Sgn
- Sin
- Sleep
- SpanExcluding
- SpanIncluding
- SpreadsheetAddAutoFilter
- SpreadsheetAddColumn
- SpreadsheetAddFreezePane
- SpreadsheetAddImage
- SpreadsheetAddInfo
- SpreadsheetAddPageBreaks
- SpreadsheetAddRow
- SpreadsheetAddRows
- SpreadsheetAddSplitPane
- SpreadsheetCreateSheet
- SpreadsheetDeleteColumn
- SpreadsheetDeleteColumns
- SpreadsheetDeleteRow
- SpreadsheetDeleteRows
- SpreadsheetFormatCell
- SpreadsheetFormatColumn
- SpreadsheetFormatCellRange
- SpreadsheetFormatColumn
- SpreadsheetFormatColumns
- SpreadsheetFormatRow
- SpreadsheetFormatRows
- SpreadsheetGetCellComment
- SpreadsheetGetCellFormula
- SpreadsheetGetCellValue
- SpreadsheetGetColumnCount
- SpreadsheetInfo
- SpreadsheetMergeCells
- SpreadsheetNew
- SpreadsheetRead
- SpreadsheetReadBinary
- SpreadsheetRemoveSheet
- SpreadsheetSetActiveSheet
- SpreadsheetSetActiveSheetNumber
- SpreadsheetSetCellComment
- SpreadsheetSetCellFormula
- SpreadsheetSetCellValue
- SpreadsheetSetColumnWidth
- SpreadsheetSetFooter
- SpreadsheetSetHeader
- SpreadsheetSetRowHeight
- SpreadsheetShiftColumns
- SpreadsheetShiftRows
- SpreadsheetWrite
- StreamingSpreadsheetNew
- StreamingSpreadsheetCleanup
- StreamingSpreadsheetRead
- StreamingSpreadsheetProcess
- SpreadsheetSetFooterImage
- SpreadsheetSetHeaderImage
- SpreadsheetSetFittoPage
- SpreadsheetUngroupColumns
- SpreadsheetGroupColumns
- SpreadsheetUngroupRows
- SpreadsheetGroupRows
- SpreadsheetRemoveColumnBreak
- SpreadsheetSetColumnBreak
- SpreadsheetRemoveRowBreak
- SpreadsheetSetRowBreak
- SpreadsheetRemovePrintGridlines
- SpreadsheetAddPrintGridlines
- SpreadsheetGetColumnWidth
- SpreadsheetSetColumnHidden
- SpreadsheetSetRowHidden
- SpreadsheetisColumnHidden
- SpreadsheetisRowHidden
- SpreadsheetisStreamingXmlFormat
- SpreadsheetisXmlFormat
- SpreadsheetisBinaryFormat
- SpreadsheetRenameSheet
- SpreadsheetRemoveSheetNumber
- SpreadsheetGetLastRowNumber
- SpreadsheetGetPrintOrientation
- Sqr
- StripCR
- StructAppend
- StructClear
- StructCopy
- StructCount
- StructDelete
- StructEach
- StructFilter
- StructFind
- StructFindKey
- StructFindValue
- StructGet
- StructGetMetadata
- StructInsert
- StructIsEmpty
- StructKeyArray
- StructKeyExists
- StructKeyList
- StructMap
- StructNew
- StructReduce
- StructSetMetadata
- StructSort
- StructToSorted
- StructUpdate
- StructValueArray
- StoreSetMetadata
- StoreGetACL
- StoreGetMetadata
- StoreAddACL
- StoreSetACL
- Functions-t-z
- Tan
- ThreadJoin
- ThreadTerminate
- Throw
- TimeFormat
- ToBase64
- ToBinary
- ToScript
- ToString
- Trace
- Transactionandconcurrency
- TransactionCommit
- TransactionRollback
- TransactionSetSavePoint
- Trim
- UCase
- URLDecode
- URLEncodedFormat
- URLSessionFormat
- Val
- ValueList
- VerifyClient
- Week
- Wrap
- WriteDump
- WriteLog
- WriteOutput
- WSGetAllChannels
- WSGetSubscribers
- WSPublish
- WSSendMessage
- XmlChildPos
- XmlElemNew
- XmlFormat
- XmlGetNodeType
- XmlNew
- XmlParse
- XmlSearch
- XmlTransform
- XmlValidate
- Year
- YesNoFormat
- ColdFusion tags
- ColdFusion tag summary
- ColdFusion tags by category
- Application framework tags
- Communications tags
- Database manipulation tags
- Data output tags
- Debugging tags
- Exception handling tags
- Extensibility tags
- File management tags
- Flow-control tags
- Forms tags
- Internet Protocol tags
- Page processing tags
- Security tags
- Variable manipulation tags
- Other tags
- Tags a-b
- Tags c
- cfcache
- cfcalendar
- cfcase
- cfcatch
- cfchart
- cfchart tag in ColdFusion
- Get started with cfchart
- Customize a chart using cfchart
- Advanced cfchart customization options
- Create an area chart in ColdFusion
- Create line charts in ColdFusion
- Create bar charts in ColdFusion
- Create floating bar charts in ColdFusion
- Create histograms in ColdFusion
- Create pie charts in ColdFusion
- Create funnel charts in ColdFusion
- Create pyramid charts in ColdFusion
- Create curve charts in ColdFusion
- Create boxplots in ColdFusion
- Create donut charts in ColdFusion
- Create bubble charts in ColdFusion
- Create scatterplots in ColdFusion
- Create radar charts in ColdFusion
- Other chart types in ColdFusion (Cone, Cylinder, Piano, and Bullet)
- Advanced customization options in cfchart
- cfchartdata
- cfchartseries
- cfchartset
- cfclient
- cfclientsettings
- cfcol
- cfcollection
- cfcomponent
- cfcontent
- cfcontinue
- cfcookie
- Tags f
- cffeed
- cffile
- cffile action = "append"
- cffile action = "copy"
- cffile action = "delete"
- cffile action = "move"
- cffile action = "read"
- cffile action = "readBinary"
- cffile action = "rename"
- cffile action = "upload"
- cffile action = "uploadAll"
- cffile action = "write"
- cffileupload
- cffinally
- cfflush
- cfform
- cfformgroup
- cfformitem
- cfftp
- cfftp: Connection: file and directory operations
- cfftp: Opening and closing FTP server connections
- cfftp : Opening and closing secure FTP server connections
- cfftp action = "listDir"
- cffunction
- Tags g-h
- Tags i
- Tags j-l
- cfjava
- cflayout
- cflayoutarea
- cfldap
- cflocation
- cflock
- cflog
- cflogin
- cfloginuser
- cflogout
- cfloop
- cfloop : conditional loop
- cfloop : index loop
- cfloop : looping over a COM collection or structure
- cfloop : looping over a date or time range
- cfloop : looping over a list, a file, or an array
- cfloop : looping over a query
- Tags m-o
- cfmail
- cfmailparam
- cfmailpart
- cfmap
- cfmapitem
- cfmediaplayer
- cfmenu
- cfmenuitem
- cfmessagebox
- cfmodule
- cfNTauthenticate
- cfoauth
- cfobject
- cfobject: .NET object
- cfobject: COM object
- cfobject: component object
- cfobject: CORBA object
- cfobject: Java or EJB object
- cfobject: web service object
- cfobjectcache
- cfoutput
- Tags p-q
- Tags r-s
- Tags t
- Tags u-z
- CFML Reference
- Reserved words and variables
- Ajax JavaScript functions
- Ajax JavaScript functions
- Function summary Ajax
- ColdFusion.Ajax.submitForm
- ColdFusion.Autosuggest.getAutosuggestObject
- ColdFusion.Layout.enableSourceBind
- ColdFusion.MessageBox.getMessageBoxObject
- ColdFusion.ProgressBar.getProgressBarObject
- ColdFusion.MessageBox.isMessageBoxDefined
- JavaScriptFunctionsinColdFusion9Update1
- ColdFusion ActionScript functions
- ColdFusion mobile functions
- Application.cfc reference
- Script functions implemented as CFCs
- ColdFusion Flash Form style reference
- Styles valid for all controls
- Styles for cfform
- Styles for cfformgroup with horizontal or vertical type attributes
- Styles for box-style cfformgroup elements
- Styles for cfformgroup with accordion type attribute
- Styles for cfformgroup with tabnavigator type attribute
- Styles for cfformitem with hrule or vrule type attributes
- Styles for cfinput with radio, checkbox, button, image, or submit type attributes
- Styles for cftextarea tag and cfinput with text, password, or hidden type attributes
- Styles for cfselect with size attribute value of 1
- Styles for cfselect with size attribute value greater than 1
- Styles for cfcalendar tag and cfinput with dateField type attribute
- Styles for the cfgrid tag
- Styles for the cftree tag
- ColdFusion Flash Form Style Reference
- ColdFusion event gateway reference
- ColdFusion Event Gateway reference
- addEvent
- CFEvent
- CFEventclass
- Constructor
- Gateway development interfaces and classes
- getStatus
- setCFCPath
- setCFCMethod
- getOriginatorID
- getLogger
- getBuddyList
- getBuddyInfo
- IM gateway message sending commands
- IM Gateway GatewayHelper class methods
- onIncomingMessage
- onIMServerMessage
- onBuddyStatus
- onAddBuddyResponse
- onAddBuddyRequest
- IM Gateway CFC incoming message methods
- IM gateway methods and commands
- CFML CFEvent structure
- warn
- info
- setOriginatorID
- data command
- submit Multi command
- submit command
- setGatewayType
- setGatewayID
- setData
- setCFCListeners
- outgoingMessage
- getStatusTimeStamp
- numberOfMessagesReceived
- numberOfMessagesSent
- removeBuddy
- removeDeny
- removePermit
- setNickName
- setPermitMode
- setStatus
- SMS Gateway CFEvent structure and commands
- SMS Gateway incoming message CFEvent structure
- getStatusAsString
- getProtocolName
- getPermitMode
- getPermitList
- getNickName
- getName
- getDenyList
- getCustomAwayMessage
- getQueueSize
- getMaxQueueSize
- getHelper
- getGatewayType
- getGatewayServices
- getGatewayID_1
- getGatewayID
- getData
- getCFCTimeout
- setCFCTimeout
- getCFCPath
- getCFCMethod
- GatewayServices class
- Gateway interface
- GatewayHelper interface
- addPermit
- addDeny
- addBuddy
- error
- debug
- Logger class
- stop
- start
- CFML event gateway SendGatewayMessage data parameter
- restart
- fatal
- SMS gateway message sending commands
- ColdFusion C++ CFX Reference
- ColdFusion Java CFX reference
- WDDX JavaScript Objects
- Cloud services
- ColdFusion and GCP Storage
- ColdFusion and GCP Firestore
- ColdFusion and GCP PubSub
- ColdFusion and Amazon S3
- ColdFusion and DynamoDB
- ColdFusion and Amazon SQS
- ColdFusion and Amazon SNS
- ColdFusion and MongoDB
- ColdFusion and Azure Blob
- ColdFusion and Azure Service Bus
- Multi-cloud storage services
- Multi-cloud RDS databases
- ColdFusion and Azure Cosmos DB
Description
Defines web browser cookie variables, including expiration and security options.
Category
Forms tags, Variable manipulation tags
Syntax
<cfcookie name = "cookie name" samesite="Strict | Lax | None" domain = ".domain" expires = "period" httponly = "yes|no" path = "URL" secure = "yes|no" value = "text" encodevalue = "yes|no" preserveCase = "yes|no" >
Note: You can specify this tag's attributes in an attributeCollection attribute whose value is a structure. Specify the structure name in the attributeCollection attribute and use the tag's attribute names as structure keys. |
See also
cfdump, cfparam, cfregistry, cfsavecontent, cfschedule, cfset
History
ColdFusion (2025 release): Deprecated Legacy Cookie Processor support from the cfcookie tag. See Deprecated features in ColdFusion for more information.
Why was the Legacy Cookie Processor deprecated?
ColdFusion relies on Tomcat's underlying cookie processor. Starting with Tomcat 10.1, the Legacy Cookie Processor was removed and replaced with the modern RFC6265 Cookie Processor as the default. This change enforces stricter adherence to modern cookie standards.
To ensure that customer applications are not impacted by this change, ColdFusion maintains backward compatibility and continues to support the Legacy Cookie Processor for CF2025.
For more information, refer to the Tomcat Legacy Cookie Processor and standard RFC 6265 cookie processor documentation.
ColdFusion (2018 release) Update 9 and ColdFusion (2016 release) Update 15: Added attribute SameSite.
ColdFusion 10: Added the preserveCase and encodeValue attributes.
ColdFusion MX 6.1:
- Changed the expires attribute: it now accepts a date time object.
- Cookie names can include all ASCII characters except commas, semicolons, or whitespace characters.
ColdFusion 9: Added the attribute httponly.
Attributes
Attribute |
Req/Opt |
Default |
Description |
|
|---|---|---|---|---|
name |
Required |
|
Name of cookie variable. ColdFusion converts cookie names to all-uppercase. Cookie names set using this tag can include any printable ASCII characters except commas, semicolons, or white space characters. |
|
domain |
Required if path attribute is specified. Optional otherwise |
|
Domain in which cookie is valid and to which cookie content can be sent from the user's system. By default, the cookie is only available to the server that set it. Use this attribute to make the cookie available to other servers.Must start with a period. If the value is a subdomain, the valid domain is all domain names that end with this string. This attribute sets the available subdomains on the site on which the cookie can be used. |
|
encodevalue |
Optional |
|
Specify if cookie value should be encoded |
|
expires |
Optional |
session only |
Expiration of cookie variable.
|
|
httponly |
Optional |
|
If yes, sets cookie as httponly so that it cannot be accessed using JavaScripts. Note that the browser must have httponly compatibility. |
|
path |
Optional |
|
URL, within a domain, to which the cookie applies; typically a directory. Only pages in this path can use the cookie. By default, all pages on the server that set the cookie can access the cookie.
To specify multiple URLs, use multiple cfcookie tags. If you specify path, also specify domain. |
|
preserveCase |
Optional |
False |
Specify if cookie name should be case-sensitive. |
|
secure |
Optional |
|
If browser does not support Secure Sockets Layer (SSL) security, the cookie is not sent. To use the cookie, the page must be accessed using the https protocol.
|
|
value
samesite |
Optional
Optional |
|
Value to assign to cookie variable. Must be a string or variable that can be stored as a string.
The SameSite attribute tells browsers when and how to fire cookies in first- or third-party situations. SameSite is used by a variety of browsers to identify whether or not to allow a cookie to be accessed. Values- "Strict | Lax | None". |
Usage
If this tag specifies that a cookie is saved beyond the current browser session, the client browser writes or updates the cookie in its local cookies file. Until the browser is closed, the cookie resides in browser memory. If the expires attribute is not specified, the cookie is not written to the browser cookies file.
If you use this tag after the cfflush tag on a page, ColdFusion does not send the cookie to the browser; however, the value you set is available to ColdFusion in the Cookie scope during the browser session.
Note: You can also create a cookie that expires when the current browser session expires by using the cfset tag or a CFScript assignment statement to set a variable in the Cookie scope, as in <cfset Cookie.mycookie="sugar">. To get a cookie's value, refer to the cookie name in the Cookie scope, as in <cfif Cookie.mycookie is "oatmeal">. |
You can use dots in cookie names, as the following examples show:
<cfcookie name="person.name" value="wilson, john"> |
To access cookies, including cookies that you set and all cookies that are sent by the client, use the Cookie scope. For example, to display the value of the person.name cookie set in the preceding code, use the following line:
<cfoutput>#cookie.person.name#</cfoutput> |
Example
<!--- This example shows how to set/delete a cfcookie variable. --->
<!--- Select users who have entered comments into a sample database. --->
<cfquery name = "GetAolUser" dataSource = "cfdocexamples">
SELECT EMail, FromUser, Subject, Posted
FROM Comments
</cfquery>
<html>
<body>
<h3>cfcookie Example</h3>
<!--- If the URL variable delcookie exists, set cookie expiration date
to NOW --->
<cfif IsDefined("url.delcookie") is True>
<cfcookie name = "TimeVisited"
value = "#Now()#"
expires = "NOW">
<cfelse>
<!--- Otherwise, loop through list of visitors; stop when you match
the string aol.com in a visitor's e-mail address. --->
<cfloop query = "GetAolUser">
<cfif FindNoCase("aol.com", Email, 1) is not 0>
<cfcookie name = "LastAOLVisitor"
value = "#Email#"
expires = "NOW" >
</cfif>
</cfloop>
<!--- If the timeVisited cookie is not set, set a value. --->
<cfif IsDefined("Cookie.TimeVisited") is False>
<cfcookie name = "TimeVisited"
value = "#Now()#"
expires = "10">
</cfif>
</cfif>
<!--- Show the most recent cookie set. --->
<cfif IsDefined("Cookie.LastAOLVisitor") is "True">
<p>The last AOL visitor to view this site was
<cfoutput>#Cookie.LastAOLVisitor#</cfoutput>, on
<cfoutput>#DateFormat(COOKIE.TimeVisited)#</cfoutput>
<!--- Use this link to reset the cookies. --->
<p><a href = "cfcookie.cfm?delcookie = yes">Hide my tracks</A>
<cfelse>
<p>No AOL Visitors have viewed the site lately.
</cfif>
Real-world uses of the cfcookie tag
User Interface personalization
Modern web applications need to remember individual user preferences like theme selection (dark mode/light mode), language choice, font size, and layout settings across multiple visits without requiring user accounts or database storage. These preferences enhance user experience by maintaining visual consistency and accessibility settings between sessions, allowing users to customize their interface once and have those choices persist automatically on return visits through cookie-based preference storage.
Problem statement
- Users forced to reconfigure interface preferences (theme, font size) on every visit
- No user account system available to store preference data in database
- Session scope preferences lost when browser closes requiring daily reconfiguration
- Accessibility settings like high contrast or large fonts not persisting across sessions
Solution
This sample demonstrates using cfcookie to store user interface preferences where theme selection, font size, and layout choices are saved as persistent cookies with long expiration dates (30-365 days) allowing preferences to survive browser restarts and persist across visits.
<cfparam name="url.action" default="view">
<!--- Read existing preferences from cookies --->
<cfparam name="cookie.userTheme" default="light">
<cfparam name="cookie.fontSize" default="medium">
<cfparam name="cookie.layout" default="compact">
<!--- Handle preference updates --->
<cfif url.action EQ "update" AND structKeyExists(form, "theme")>
<!--- Save theme preference for 1 year --->
<cfcookie
name="userTheme"
value="#form.theme#"
expires="365"
httponly="true"
samesite="Lax"
preserveCase="false">
<!--- Save font size preference --->
<cfcookie
name="fontSize"
value="#form.fontSize#"
expires="365"
httponly="true"
samesite="Lax">
<!--- Save layout preference --->
<cfcookie
name="layout"
value="#form.layout#"
expires="365"
httponly="true"
samesite="Lax">
<!--- Redirect to apply changes --->
<script>window.location.href = '01_user_preferences_theme.cfm';</script>
<cfabort>
</cfif>
<!--- Handle reset preferences --->
<cfif url.action EQ "reset">
<!--- Delete cookies by setting expires="NOW" --->
<cfcookie name="userTheme" value="" expires="NOW">
<cfcookie name="fontSize" value="" expires="NOW">
<cfcookie name="layout" value="" expires="NOW">
<script>window.location.href = '01_user_preferences_theme.cfm';</script>
<cfabort>
</cfif>
<!--- Apply theme settings --->
<cfset currentTheme = cookie.userTheme>
<cfset currentFontSize = cookie.fontSize>
<cfset currentLayout = cookie.layout>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>User Preferences - Cookie Demo</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
/* Light Theme */
body.light {
background: ##f5f5f5;
color: ##333;
}
/* Dark Theme */
body.dark {
background: ##1a1a1a;
color: ##e0e0e0;
}
/* High Contrast Theme */
body.high-contrast {
background: ##000;
color: ##fff;
}
.container {
max-width: 1000px;
margin: 0 auto;
padding: 20px;
}
.header {
padding: 40px;
border-radius: 15px;
margin-bottom: 20px;
text-align: center;
}
body.light .header {
background: linear-gradient(135deg, ##667eea 0%, ##764ba2 100%);
color: white;
}
body.dark .header {
background: linear-gradient(135deg, ##434343 0%, ##000000 100%);
color: ##e0e0e0;
border: 1px solid ##444;
}
body.high-contrast .header {
background: ##fff;
color: ##000;
border: 3px solid ##fff;
}
.content {
padding: 30px;
border-radius: 10px;
margin-bottom: 20px;
}
body.light .content {
background: white;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
body.dark .content {
background: ##2d2d2d;
border: 1px solid ##444;
}
body.high-contrast .content {
background: ##000;
border: 3px solid ##fff;
}
.pref-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
margin: 20px 0;
}
.pref-card {
padding: 20px;
border-radius: 10px;
border: 2px solid transparent;
}
body.light .pref-card {
background: ##f8f9fa;
border-color: ##e0e0e0;
}
body.dark .pref-card {
background: ##1a1a1a;
border-color: ##444;
}
body.high-contrast .pref-card {
background: ##000;
border-color: ##fff;
}
.pref-label {
font-weight: bold;
margin-bottom: 10px;
display: block;
}
select, button {
width: 100%;
padding: 10px;
border-radius: 5px;
border: 2px solid ##ccc;
font-size: 14px;
}
body.dark select, body.dark button {
background: ##333;
color: ##e0e0e0;
border-color: ##555;
}
body.high-contrast select, body.high-contrast button {
background: ##000;
color: ##fff;
border: 3px solid ##fff;
font-weight: bold;
}
.btn-primary {
background: ##667eea;
color: white;
border: none;
cursor: pointer;
margin-top: 10px;
transition: all 0.3s;
}
.btn-primary:hover {
background: ##5568d3;
transform: translateY(-2px);
}
.btn-secondary {
background: ##6c757d;
color: white;
border: none;
cursor: pointer;
margin-top: 10px;
}
/* Font Size Variations */
body.font-small { font-size: 14px; }
body.font-medium { font-size: 16px; }
body.font-large { font-size: 18px; }
body.font-xlarge { font-size: 20px; }
/* Layout Variations */
.container.compact { max-width: 800px; }
.container.normal { max-width: 1000px; }
.container.wide { max-width: 1400px; }
.cookie-info {
padding: 15px;
border-radius: 8px;
margin-top: 20px;
font-family: 'Courier New', monospace;
font-size: 13px;
}
body.light .cookie-info {
background: ##fff3cd;
border-left: 4px solid ##ffc107;
}
body.dark .cookie-info {
background: ##2d2d2d;
border-left: 4px solid ##ffc107;
}
body.high-contrast .cookie-info {
background: ##000;
border: 3px solid ##fff;
}
</style>
</head>
<body class="<cfoutput>#currentTheme# font-#currentFontSize#</cfoutput>">
<div class="container <cfoutput>#currentLayout#</cfoutput>">
<div class="header">
<h1>🎨 User Preferences Demo</h1>
<p>Your preferences are saved in cookies and persist across visits</p>
</div>
<div class="content">
<h2>Customize Your Experience</h2>
<p style="margin: 15px 0;">
Select your preferred theme, font size, and layout. Your choices will be
saved for 1 year using cookies.
</p>
<form method="post" action="?action=update">
<div class="pref-grid">
<div class="pref-card">
<label class="pref-label">Theme</label>
<select name="theme">
<cfoutput>
<option value="light" #currentTheme EQ 'light' ? 'selected' : ''#>☀️ Light</option>
<option value="dark" #currentTheme EQ 'dark' ? 'selected' : ''#>🌙 Dark</option>
<option value="high-contrast" #currentTheme EQ 'high-contrast' ? 'selected' : ''#>👁️ High Contrast</option>
</cfoutput>
</select>
</div>
<div class="pref-card">
<label class="pref-label">Font Size</label>
<select name="fontSize">
<cfoutput>
<option value="small" #currentFontSize EQ 'small' ? 'selected' : ''#>Small (14px)</option>
<option value="medium" #currentFontSize EQ 'medium' ? 'selected' : ''#>Medium (16px)</option>
<option value="large" #currentFontSize EQ 'large' ? 'selected' : ''#>Large (18px)</option>
<option value="xlarge" #currentFontSize EQ 'xlarge' ? 'selected' : ''#>Extra Large (20px)</option>
</cfoutput>
</select>
</div>
<div class="pref-card">
<label class="pref-label">Layout Width</label>
<select name="layout">
<cfoutput>
<option value="compact" #currentLayout EQ 'compact' ? 'selected' : ''#>Compact (800px)</option>
<option value="normal" #currentLayout EQ 'normal' ? 'selected' : ''#>Normal (1000px)</option>
<option value="wide" #currentLayout EQ 'wide' ? 'selected' : ''#>Wide (1400px)</option>
</cfoutput>
</select>
</div>
</div>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 20px;">
<button type="submit" class="btn-primary">💾 Save Preferences</button>
<button type="button" class="btn-secondary" onclick="window.location='?action=reset'">
🔄 Reset to Defaults
</button>
</div>
</form>
</div>
<div class="content">
<h3>🍪 Current Cookie Values</h3>
<div class="cookie-info">
<cfoutput>
<strong>Cookie: userTheme</strong> = #cookie.userTheme#<br>
<strong>Cookie: fontSize</strong> = #cookie.fontSize#<br>
<strong>Cookie: layout</strong> = #cookie.layout#<br>
<br>
<em>These cookies expire in 365 days and are HttpOnly for security.</em>
</cfoutput>
</div>
</div>
</div>
</body>
</html>
E-Commerce shopping cart session management
E-commerce platforms require persistent shopping cart functionality where users can add products, browse other pages, close their browser, and return days later to find their cart items still waiting for checkout. Traditional session-based carts lose data when sessions expire or browsers close, but cookie-based cart tracking maintains cart contents across multiple visits, devices, and browser sessions allowing customers to shop at their own pace without losing selections or requiring immediate account creation.
Problem statement
- Session-based shopping carts lost when user closes browser before completing purchase
- Cart abandonment rates increase when users must recreate selections after session timeout
- Guest checkout users cannot maintain cart state across multiple browsing sessions
- No way to track cart items without forcing immediate user account creation
- Marketing campaigns cannot retarget users with abandoned cart reminders effectively
Solution
his sample demonstrates using cfcookie to maintain shopping cart state where each added product stores its cart item ID in a persistent cookie with 7-30 day expiration allowing cart recovery across browser sessions and device switches. The cfcookie secure attribute protects cart data during transmission, cart items are stored as pipe-delimited strings or JSON for multiple product tracking, and the application reconstructs cart contents from cookies on each page.
<cfparam name="url.action" default="view">
<!--- Initialize cart from cookie --->
<cfparam name="cookie.cartItems" default="">
<cfparam name="cookie.cartId" default="">
<!--- Generate cart ID if doesn't exist --->
<cfif cookie.cartId EQ "">
<cfset newCartId = "CART-" & createUUID()>
<cfcookie
name="cartId"
value="#newCartId#"
expires="30"
httponly="true"
samesite="Lax">
<cfset cookie.cartId = newCartId>
</cfif>
<!--- Product catalog --->
<cfset products = {
"PROD001" = {name = "Wireless Headphones", price = 79.99, emoji = "🎧"},
"PROD002" = {name = "Laptop Stand", price = 49.99, emoji = "💻"},
"PROD003" = {name = "Mechanical Keyboard", price = 129.99, emoji = "⌨️"},
"PROD004" = {name = "Webcam HD", price = 89.99, emoji = "📷"},
"PROD005" = {name = "Mouse Pad XL", price = 24.99, emoji = "🖱️"}
}>
<!--- Parse cart items from cookie --->
<cfset cartItems = []>
<cfif len(trim(cookie.cartItems)) GT 0>
<cfset cartItemIds = listToArray(cookie.cartItems, "|")>
<cfloop array="#cartItemIds#" index="productId">
<cfif structKeyExists(products, productId)>
<cfset arrayAppend(cartItems, {
id = productId,
name = products[productId].name,
price = products[productId].price,
emoji = products[productId].emoji
})>
</cfif>
</cfloop>
</cfif>
<!--- Handle add to cart --->
<cfif url.action EQ "add" AND structKeyExists(url, "productId")>
<cfset productId = url.productId>
<cfif structKeyExists(products, productId)>
<!--- Add product to cart cookie --->
<cfif len(trim(cookie.cartItems)) GT 0>
<cfset updatedCart = cookie.cartItems & "|" & productId>
<cfelse>
<cfset updatedCart = productId>
</cfif>
<cfcookie
name="cartItems"
value="#updatedCart#"
expires="30"
httponly="true"
samesite="Lax">
<script>window.location.href = '02_shopping_cart_tracking.cfm';</script>
<cfabort>
</cfif>
</cfif>
<!--- Handle remove from cart --->
<cfif url.action EQ "remove" AND structKeyExists(url, "index")>
<cfset removeIndex = url.index>
<cfset cartItemIds = listToArray(cookie.cartItems, "|")>
<cfset arrayDeleteAt(cartItemIds, removeIndex)>
<cfset updatedCart = arrayToList(cartItemIds, "|")>
<cfcookie
name="cartItems"
value="#updatedCart#"
expires="30"
httponly="true"
samesite="Lax">
<script>window.location.href = '02_shopping_cart_tracking.cfm';</script>
<cfabort>
</cfif>
<!--- Handle clear cart --->
<cfif url.action EQ "clear">
<cfcookie name="cartItems" value="" expires="NOW">
<script>window.location.href = '02_shopping_cart_tracking.cfm';</script>
<cfabort>
</cfif>
<!--- Calculate cart totals --->
<cfset cartTotal = 0>
<cfloop array="#cartItems#" index="item">
<cfset cartTotal += item.price>
</cfloop>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Shopping Cart - Cookie Tracking</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, ##667eea 0%, ##764ba2 100%);
min-height: 100vh; padding: 20px; }
.container { max-width: 1200px; margin: 0 auto; }
.header { background: white; padding: 40px; border-radius: 15px 15px 0 0;
text-align: center; box-shadow: 0 5px 20px rgba(0,0,0,0.1); }
.header h1 { color: ##2c3e50; font-size: 32px; margin-bottom: 10px; }
.cart-info { background: ##fff3cd; padding: 15px; border-radius: 8px;
margin-top: 15px; border-left: 4px solid ##ffc107; }
.content { background: white; padding: 40px; border-radius: 0 0 15px 15px;
box-shadow: 0 10px 40px rgba(0,0,0,0.2); }
.product-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 20px; margin: 30px 0; }
.product-card { background: ##f8f9fa; padding: 25px; border-radius: 10px;
border: 2px solid ##e0e0e0; transition: all 0.3s; }
.product-card:hover { transform: translateY(-5px); border-color: ##667eea;
box-shadow: 0 5px 15px rgba(102,126,234,0.3); }
.product-emoji { font-size: 48px; text-align: center; margin-bottom: 15px; }
.product-name { font-weight: bold; color: ##2c3e50; margin-bottom: 10px;
font-size: 16px; }
.product-price { color: ##28a745; font-size: 24px; font-weight: bold;
margin-bottom: 15px; }
.btn { padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer;
font-size: 14px; font-weight: bold; transition: all 0.3s; width: 100%; }
.btn-add { background: ##667eea; color: white; }
.btn-add:hover { background: ##5568d3; transform: translateY(-2px); }
.btn-remove { background: ##dc3545; color: white; }
.btn-remove:hover { background: ##c82333; }
.btn-clear { background: ##6c757d; color: white; }
.btn-checkout { background: ##28a745; color: white; }
.cart-section { background: ##e7f3ff; padding: 25px; border-radius: 10px;
margin-bottom: 20px; border-left: 4px solid ##667eea; }
.cart-item { background: white; padding: 15px; border-radius: 8px;
margin-bottom: 10px; display: flex; justify-content: space-between;
align-items: center; }
.cart-item-info { display: flex; align-items: center; gap: 15px; }
.cart-total { background: ##28a745; color: white; padding: 20px;
border-radius: 10px; font-size: 24px; font-weight: bold;
text-align: center; margin: 20px 0; }
.empty-cart { text-align: center; padding: 40px; color: ##7f8c8d; }
.empty-cart-icon { font-size: 64px; margin-bottom: 20px; }
.cookie-display { background: ##2d2d2d; color: ##f8f8f2; padding: 15px;
border-radius: 8px; font-family: 'Courier New', monospace;
font-size: 12px; margin-top: 15px; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>🛒 Shopping Cart Demo</h1>
<p style="color: ##7f8c8d;">Cookie-based cart tracking - persists for 30 days!</p>
<div class="cart-info">
<cfoutput>
<strong>Cart ID:</strong> #cookie.cartId#<br>
<strong>Items in Cart:</strong> #arrayLen(cartItems)#<br>
<strong>Cart Total:</strong> #dollarFormat(cartTotal)#
</cfoutput>
</div>
</div>
<div class="content">
<h2>🛍️ Available Products</h2>
<div class="product-grid">
<cfloop collection="#products#" item="productId">
<cfset product = products[productId]>
<div class="product-card">
<cfoutput>
<div class="product-emoji">#product.emoji#</div>
<div class="product-name">#product.name#</div>
<div class="product-price">#dollarFormat(product.price)#</div>
<a href="?action=add&productId=#productId#" style="text-decoration: none;">
<button class="btn btn-add">🛒 Add to Cart</button>
</a>
</cfoutput>
</div>
</cfloop>
</div>
<h2 style="margin-top: 40px;">🛒 Your Shopping Cart</h2>
<div class="cart-section">
<cfif arrayLen(cartItems) GT 0>
<cfloop array="#cartItems#" index="i" item="item">
<div class="cart-item">
<cfoutput>
<div class="cart-item-info">
<span style="font-size: 32px;">#item.emoji#</span>
<div>
<div style="font-weight: bold; color: ##2c3e50;">#item.name#</div>
<div style="color: ##28a745; font-size: 18px; font-weight: bold;">
#dollarFormat(item.price)#
</div>
</div>
</div>
<a href="?action=remove&index=#i#" style="text-decoration: none;">
<button class="btn btn-remove">❌ Remove</button>
</a>
</cfoutput>
</div>
</cfloop>
<cfoutput>
<div class="cart-total">
Total: #dollarFormat(cartTotal)#
</div>
</cfoutput>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
<button class="btn btn-checkout" onclick="alert('Proceeding to checkout!')">
💳 Checkout
</button>
<a href="?action=clear" style="text-decoration: none;">
<button class="btn btn-clear">🗑️ Clear Cart</button>
</a>
</div>
<cfelse>
<div class="empty-cart">
<div class="empty-cart-icon">🛒</div>
<h3>Your cart is empty</h3>
<p>Add some products to get started!</p>
</div>
</cfif>
</div>
<h3>🍪 Cookie Implementation Details</h3>
<div class="cookie-display">
<cfoutput>Cookie: cartId = #cookie.cartId#
Cookie: cartItems = #cookie.cartItems#
Cart expires in: 30 days
Security: HttpOnly = true, SameSite = Lax
Storage format: Pipe-delimited product IDs
Benefits:
- Cart persists across browser sessions
- No user account required
- Works for guest checkout
- Enables abandoned cart recovery</cfoutput>
</div>
</div>
</div>
</body>
</html>
Persistent authentication system- Remember Me
User authentication systems need Remember Me functionality where users can opt to stay logged in across browser sessions without re-entering credentials on each visit, balancing convenience with security through encrypted remember-me tokens stored in long-lived cookies that automatically restore authentication state. This feature increases user engagement by reducing login friction while maintaining security through token rotation, device fingerprinting, and configurable expiration periods based on risk assessment and compliance requirements.
Problem statement
- Users frustrated by constant re-authentication requests on trusted personal devices
- Session-only authentication expires immediately when browser closes requiring daily logins
- Password managers not available or not used by all users causing login abandonment
- Mobile app users switching between apps lose authentication state due to session timeout
- Enterprise applications need extended sessions for productivity without compromising security
Solution
This sample demonstrates using cfcookie to implement secure "Remember Me" functionality where user selection at login creates an encrypted remember-me token stored in a cookie with 14-90 day expiration, the token contains user identifier and device fingerprint preventing token theft, httponly and secure attributes protect cookie data from XSS attacks.
<cfparam name="url.action" default="view">
<cfparam name="cookie.rememberToken" default="">
<cfparam name="cookie.rememberUser" default="">
<!--- Simulated user database --->
<cfset users = {
"user@example.com" = {
password = hash("password123", "SHA-256"),
name = "John Doe",
lastLogin = now()
},
"admin@example.com" = {
password = hash("admin456", "SHA-256"),
name = "Jane Admin",
lastLogin = now()
}
}>
<!--- Check if user is remembered --->
<cfset isRemembered = false>
<cfset currentUser = "">
<cfif len(trim(cookie.rememberToken)) GT 0 AND len(trim(cookie.rememberUser)) GT 0>
<!--- Validate remember token (in production, validate against database) --->
<cfset expectedToken = hash(cookie.rememberUser & "SECRET_KEY", "SHA-256")>
<cfif cookie.rememberToken EQ expectedToken AND structKeyExists(users, cookie.rememberUser)>
<cfset isRemembered = true>
<cfset currentUser = cookie.rememberUser>
</cfif>
</cfif>
<!--- Handle login --->
<cfif url.action EQ "login" AND structKeyExists(form, "email")>
<cfset loginEmail = trim(form.email)>
<cfset loginPassword = trim(form.password)>
<cfset rememberMe = structKeyExists(form, "remember") AND form.remember EQ "true">
<cfif structKeyExists(users, loginEmail)>
<cfset hashedPassword = hash(loginPassword, "SHA-256")>
<cfif users[loginEmail].password EQ hashedPassword>
<!--- Login successful --->
<cfif rememberMe>
<!--- Create remember-me token --->
<cfset rememberToken = hash(loginEmail & "SECRET_KEY", "SHA-256")>
<cfcookie
name="rememberToken"
value="#rememberToken#"
expires="30"
httponly="true"
secure="false"
samesite="Strict">
<cfcookie
name="rememberUser"
value="#loginEmail#"
expires="30"
httponly="true"
secure="false"
samesite="Strict">
</cfif>
<script>window.location.href = '03_remember_me_login.cfm';</script>
<cfabort>
</cfif>
</cfif>
<cfset loginError = "Invalid email or password">
</cfif>
<!--- Handle logout --->
<cfif url.action EQ "logout">
<cfcookie name="rememberToken" value="" expires="NOW">
<cfcookie name="rememberUser" value="" expires="NOW">
<script>window.location.href = '03_remember_me_login.cfm';</script>
<cfabort>
</cfif>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Remember Me Login - Cookie Demo</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, ##11998e 0%, ##38ef7d 100%);
min-height: 100vh; padding: 20px; display: flex; align-items: center;
justify-content: center; }
.container { max-width: 500px; width: 100%; }
.card { background: white; border-radius: 15px; padding: 40px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3); }
.card h1 { color: ##2c3e50; margin-bottom: 10px; text-align: center; }
.card p { color: ##7f8c8d; text-align: center; margin-bottom: 30px; }
.form-group { margin-bottom: 20px; }
.form-label { display: block; font-weight: bold; color: ##2c3e50;
margin-bottom: 8px; }
.form-input { width: 100%; padding: 12px; border: 2px solid ##e0e0e0;
border-radius: 8px; font-size: 14px; transition: all 0.3s; }
.form-input:focus { outline: none; border-color: ##11998e; }
.checkbox-group { display: flex; align-items: center; gap: 10px;
margin: 15px 0; }
.checkbox-group input[type="checkbox"] { width: 18px; height: 18px;
cursor: pointer; }
.checkbox-group label { cursor: pointer; color: ##2c3e50; }
.btn { width: 100%; padding: 15px; border: none; border-radius: 8px;
font-size: 16px; font-weight: bold; cursor: pointer; transition: all 0.3s; }
.btn-login { background: linear-gradient(135deg, ##11998e 0%, ##38ef7d 100%);
color: white; }
.btn-login:hover { transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(17,153,142,0.4); }
.btn-logout { background: ##dc3545; color: white; }
.btn-logout:hover { background: ##c82333; }
.welcome-section { text-align: center; padding: 20px; }
.welcome-icon { font-size: 64px; margin-bottom: 20px; }
.welcome-name { font-size: 28px; color: ##2c3e50; font-weight: bold;
margin-bottom: 10px; }
.status-badge { display: inline-block; padding: 8px 20px; border-radius: 20px;
font-size: 14px; font-weight: bold; margin: 15px 0; }
.badge-remembered { background: ##d4edda; color: ##155724; }
.badge-session { background: ##fff3cd; color: ##856404; }
.info-panel { background: ##e7f3ff; padding: 20px; border-radius: 10px;
border-left: 4px solid ##11998e; margin-top: 20px; }
.cookie-display { background: ##2d2d2d; color: ##f8f8f2; padding: 15px;
border-radius: 8px; font-family: 'Courier New', monospace;
font-size: 12px; margin-top: 15px; }
.demo-creds { background: ##fff3cd; padding: 15px; border-radius: 8px;
margin-bottom: 20px; border-left: 4px solid ##ffc107; }
.error-msg { background: ##f8d7da; color: ##721c24; padding: 12px;
border-radius: 8px; margin-bottom: 15px; border-left: 4px solid ##dc3545; }
</style>
</head>
<body>
<div class="container">
<div class="card">
<cfif isRemembered>
<!--- User is automatically logged in via remember-me cookie --->
<div class="welcome-section">
<div class="welcome-icon">👋</div>
<cfoutput>
<div class="welcome-name">Welcome back, #users[currentUser].name#!</div>
<p style="color: ##7f8c8d;">You were automatically logged in</p>
<span class="status-badge badge-remembered">
✓ Remembered for 30 days
</span>
</cfoutput>
</div>
<div class="info-panel">
<h3 style="color: ##2c3e50; margin-bottom: 15px;">Account Information</h3>
<cfoutput>
<p><strong>Email:</strong> #currentUser#</p>
<p><strong>Last Login:</strong> #dateTimeFormat(users[currentUser].lastLogin, "yyyy-mm-dd HH:nn:ss")#</p>
<p style="margin-top: 10px; font-size: 13px; color: ##7f8c8d;">
Your authentication is maintained using a secure remember-me cookie.
</p>
</cfoutput>
</div>
<h3 style="color: ##2c3e50; margin: 20px 0 10px 0;">🍪 Cookie Details</h3>
<div class="cookie-display">
<cfoutput>Cookie: rememberToken = #left(cookie.rememberToken, 40)#...
Cookie: rememberUser = #cookie.rememberUser#
Security Settings:
- HttpOnly = true (prevents XSS)
- Secure = false (use true in production with HTTPS)
- SameSite = Strict (prevents CSRF)
- Expires = 30 days from creation</cfoutput>
</div>
<a href="?action=logout" style="text-decoration: none;">
<button class="btn btn-logout" style="margin-top: 20px;">
🚪 Logout & Clear Remember Me
</button>
</a>
<cfelse>
<!--- Login form --->
<h1>🔐 Secure Login</h1>
<p>Demo: Remember Me functionality with cookies</p>
<div class="demo-creds">
<strong>Demo Credentials:</strong><br>
<strong>Email:</strong> user@example.com<br>
<strong>Password:</strong> password123<br>
<em style="font-size: 12px;">or admin@example.com / admin456</em>
</div>
<cfif structKeyExists(variables, "loginError")>
<div class="error-msg">
<cfoutput>❌ #loginError#</cfoutput>
</div>
</cfif>
<form method="post" action="?action=login">
<div class="form-group">
<label class="form-label">Email Address</label>
<input
type="email"
name="email"
class="form-input"
placeholder="your@email.com"
required>
</div>
<div class="form-group">
<label class="form-label">Password</label>
<input
type="password"
name="password"
class="form-input"
placeholder="Enter your password"
required>
</di
<div class="checkbox-group">
<input
type="checkbox"
name="remember"
id="remember"
value="true"
checked>
<label for="remember">
<strong>Remember me for 30 days</strong>
<br>
<small style="color: ##7f8c8d;">
Stay logged in on this device
</small>
</label>
</div>
<button type="submit" class="btn btn-login">
🔓 Login
</button>
</form>
</cfif>
</div>
</div>
</body>
</html>