may be used or copied only in accordance with the terms of such license. The content
of this manual is furnished for informational use only, is subject to change without
notice, and should not be construed as a commitment by Macromedia Incorporated.
Macromedia Incorporated assumes no responsibility or liability for any errors or
inaccuracies that may appear in this book.
Except as permitted by such license, no part of this publication may be reproduced,
stored in a retrieval system, or transmitted in any form or by any means, electronic,
mechanical, recording, or otherwise, without the prior written permission of
Macromedia Incorporated.
ColdFusion and HomeSite are federally registered trademarks of Macromedia
Incorporated. HomeSite, the ColdFusio n logo and the Allaire logo are trademarks of
Macromedia Incorporated in the USA and other countries. M icrosoft, Windows,
Windows NT, Windows 95, Microsoft Access, and FoxPro are registered trademarks of
Microsoft Corporation. Solaris is a trademark of Sun Microsystems Inc. UNIX is a
trademark of The Open Group. PostScript is a trademark of Adobe Systems Inc. All
other products or name brands are the trademarks of their respective holders.
The CFML Reference is your primary ColdFusion Markup Language (CFML) reference
guide. Use this guide to learn about individual CFML tags and functions, as well as
ColdFusion expressions, using JavaScript objects for WDDX in ColdFusion. You can
also find detailed references for Java and C++ CFX interfaces.
•Contacting Macromedia........................................................................................x viii
xvi About This Book
Intended Audience
The CFML Reference is intended for ColdFusion developers building pages and
writing CFML code.
Developer Resources
Macromedia C orpo r a tion is com mitte d to setting the standar d for custo me r sup port
in developer education , tech nical supp o rt, and pro fes sio nal services . T he Web site is
designed to give you quick access to the entire range of online resources, as the
following table describes.
ResourceDescriptionURL
Macromedia W eb
site
Information on
ColdFusion
Technical
Support
ColdFusion
Support Forum
Installation
Support
Professional
Education
Developer
Community
General information about Macromedia
products and service s
Detailed product information on
ColdFusion and related topics
Professional support programs that
Macromedia offers.
Access to experienced ColdFusion
developers through participation in the
Online Forums, where you can post
messages and read replies on many
subjects relating to ColdFusion.
Support for installation-related issues
for all Macromedia prod uc t s
Information about classes, on-site
training, and online courses offered by
Macromedia
All the resources that you need to stay
on the cutting edge of ColdFusion
development, including online
discussion groups, Knowledge Base,
technical papers and more
www.macromedia.com/
www.coldfusion.com/products/coldfusion/
www.coldfusion.com/support/
http://forums.coldfusion.com/
coldfusionconf/
www.coldfusion.com/support/installation/
www.coldfusion.com/developer/training.cfm
www.coldfusion.com/developer/
ColdFusion Dev
Center
Macromedia
Alliance
Development tips, articles,
documentation, and white papers
Connection with the growing network of
solution providers , appli ca tio n
developers, resellers, and hosting
services creating solutions with
ColdFusion
ColdFusion documentation is designed to provide support for the complete
spectrum of particip ant s . T he p rint and online ve rsio ns are organized to allow y ou t o
quickly locate the information that you need. The C oldF usion online documentation
is provided in HTML and Adobe Acrobat formats.
Printed and online documentation set
The ColdFusion documentation set consists of the following titles.
BookDescription
Installing and Configuring ColdFusion
Server
Advanced ColdFusion Admin ist rat ionDescribes how to connect your data sources to the ColdFusion
Developing ColdFusion ApplicationsDescribes how to use ColdFusion Ser ver to develop your
CFML ReferenceProvides descriptions , syntax, usage , and code example s for all
CFML Quick ReferenceA brief guide that shows the syntax of ColdFusion tags,
Describes system installation and basic configuration for
Windows NT, Windows 2000, Solaris, Linux, HP-UX.
Server , co nfi gure sec uri ty fo r you r appl ic ati ons , and how to us e
ClusterCATS to manage scalability, clustering, and
load-balancing fo r your site.
dynamic Web applications, including retrieving and updating
your data, using structures, and forms.
ColdFusion tags, functions, and variables, including WDDX,
and references for both coding Java and C++ CFXs.
functions, and variables.
Viewing online documentation
All ColdFusion documentation is available online in HTML and Adobe Acrobat PDF
formats. To view the HTML documentation, open the following URL on the Web
server running ColdFusion:
http://localhost/coldfusion/docs/dochome.htm.
To view and print ColdFusion documentation in Acrobat format, open the following
URL on the Web server running ColdFusion: http://localhost/coldfusion/docs/
AcrobatDocs/index.htm
Printing ColdFusion documentation
To read printed documentation, locate the Adobe Acrobat PDF files on the product
CD-ROM. The PDF files offer excellent print output. You can print an entire book or
individual sections.
.
xviii About This Book
Getting Answers
One of the best ways to solve particular programming problems is to tap into the vast
expertise of the ColdFusion developer communities on the ColdFusion Forums.
Other deve loper s on the f orum ca n he lp y ou fig ur e o ut how to do just about anything
with ColdFusion. The search facility can also help you search messages from the
previous 12 months, allowing you to learn how others have solved a problem that
you might be facing. The F o rums is a gr e at r es our ce for learning C o ldFu sion, bu t it is
also a great place to see the ColdFusion developer community in action.
Contacting Macromedia
Corporate
headquarters
Technical
support
Sales
Macromedia, Inc.
600 Townsend Street
San Francisco, CA 94103
Tel: 415.252.2000
Fax: 415.626.0554
Web: www. macromedia.com
Telephone support is available Monday through Friday,
8 A.M. to 8 P.M. Eastern time (except holidays)
Toll Free: 888.939.2545 (U.S. and Canada)
Tel: 617.219.2100 (outside U.S. and Canada)
Postings to the ColdFusion Support Forum (http://
forums.coldfusion.com/DevConf/index.cfm) can be
made any time.
2Chapter 1 ColdFusion Expressions: Operands, Operators and Other Constructs
Elements of ColdFusion Expressions
ColdFusion expressions consist of operands and operators. Operands are comprised
of constants and variables. Operators are the verbs that act on the op erands;
functions are a form of operator. This chapter first describes the operands and then
describes the operators.
Operands: data types, constants, and variables
The sections on operands provide detailed information on the following:
•Data types of ColdFusion operands
•ColdFusion constants
•ColdFusion variables: naming conventions, types, scoping, and other details
Data types of constants and variables
In ColdFusion, constants and variables have implied data types. The reason for the
term “implied” is that there are no variable declarations that define the scalar data
type of a variable, as one finds in statically typed languages such as Pascal. Whenever
you use a consta nt or se t the valu e o f a v ariable, the value yo u us e has a type, such as
integer, real, or string. For example, if you use
its value to 62, the implied data type is integer. In addition to these scalar types,
ColdFusion also supports lists, structures, and arrays. T h e following t able describes
the types of variables and consta nt s you can use in a Co ldFusion applicatio n page.
cfset to create a variable AGE and set
TypeDescription
IntegerNumbers with no de cimal po int. The l ower limit for a sign ed integer is
-2,147,483,648, and the upper limit for a signed integer is
2,147,483,647.
If you specify an integer outside the limits, ColdFusion converts it to
a floating point value to avoid overflow. In doing so, ColdFusion
preserves the number’s magnitude. However, the conversion to
floating point comes at the expense of precision, since ColdFusion
has only a fixed number of bits to work with.
Real numberNumbers with a decimal part. Also known as floating point numbers.
300
The range of ColdFusion numbers is approximately ±10
operations are accurate to 12 digits after the decimal point.
ColdFusion supports scientific notation; this means that you can
enter numbers in the form 3 E 16 and perform calculations on them.
. Most
Elements of ColdFusion Expressions3
TypeDescription
StringText values, which can be enc los ed in single (’) or double (") quotes.
String length is limited only by the amount of available memory on
the ColdFusion server.
To use a single quote inside a string th at is si ngle qu oted, escape, or
repeat, the single quote by using two single quotes. For example:
’the ’’best’’ software’
Similarly, you can escape a double quote inside a double
quote-enclosed string.
To insert a pound sign in a string, the pound sign must be escaped
by repeating it. For example:
"enter a pound sign (##) here"
Boolean valueThe result of a logical operation. The value can be TRUE or FALSE.
The numerical value of TRUE is 1. The numerical value of FALSE is
0. The string value of TRUE is "YES"; FALSE is "NO".
Date valueDate-and-time valu es ide nti fy a date and time in the range 100AD to
9999AD. If no time part is specified, time is set to 12:00am.
You can also enter a date object in the following formats:
The time part of the object is accurate to the second.
ArrayArrays are tables of objects or data that can be indexed. The
ArrayNew function only supports creating up to three-dimensional
arrays, there is no limit on array size or maximum dimension.
Elements stored in an array are referenced as follows:
<cfset myarray[1][2] = Now()>
For more information, see Developing ColdFusion A pplications.
StructureYou can use structures to create and maintain key-value pairs, to
refer to related string values as a unit rather than individually, or to
create associative array s.
For more information, see Developing ColdFusion A pplications.
4Chapter 1 ColdFusion Expressions: Operands, Operators and Other Constructs
TypeDescription
ListLists are a kind of string made up of elements separated by
delimiters.
The default delimitin g character used by list pro cessing function s is a
comma. A list can have more than one delimiting character. You
specify the allowable delimiters for a list in the
delimiters
parameter of ColdFusion list processing functions.
White space is not cons ider ed a deli miter. However , when using li st s
where elements may be s eparated by white space as well as by
other delimiters, add the white space characters to the list of
delimiters. Delimiters before the first element and after the last
element are ignored.
Lists cannot be nested into one another. Also, lists can contain no
empty elements. A list can be empty, however. The empty list is
equivalent to the empty string "".
QueryColdFusion queries can be referenced as objects by assigning a
query to a variable:
<cfquery name = "myquery"
datasource = "mydata"
SELECT * FROM CUSTOMERS
</cfquery>
<cfset myquery2 = myquery>
In this case the query is not copied. Both names point to the record
set data, so that if you make changes to the table referenced in the
query, the original query and the query object myquery2 both reflect
these changes. If you perform this operation with an array, the array
is copied.
Queries and var iab les cann ot h ave the same name at th e sam e time
in the same application page.
COM objectComponent Object Model (COM) objects are non-visual components
that encapsu lat e functionality tha t yo u c an inv ok e in your application
pages. ActiveX, OCX, CORBA, and ADO objects are examples of
COM objects.
COM objects generally contain methods, like functions, that you can
use to execute operations :
<cfset temp = Mailer.SendMail()>
COM objects generally contain properties you can read and write
using ColdFusion variables:
<cfset Mailer.FromName = Form.fromname>
Properties can be invoked on either side of an assignment.
For more information, see Developing ColdFusion A pplications.
Elements of ColdFusion Expressions5
Notes on date-and-time values
This section contains information about how date and time variables are handled by
ColdFusion.
How date and time values are stored
ColdFusion represents date-and-time values internally on a time line as a subset of
the real numbers. This representation is optimized for efficiency in evaluation and
because it is the method used by many popular database systems. In this model, one
day is equal to the difference between two succe ssive integers. The time portion of
the date-and-time value is stored in the fractional part of the real number.
Thus, you can use arithmetic ope ra tions to manipulate date-and-time values. For
example, Now() + 1 evaluates to tomorrow at the same time. However, we strongly
discourage ColdFusion developers from using this potentially troublesome method
of manipulating date-and-time objects. Use the date-and-time manipulation
functions instead.
21st century dates
Two-digit years from 00 to 29 are treated as 21st century dates; 30 to 99 are treated as
th
20
century dates. Thus, the following dates are equiva le nt :
"October 30, 2015"
"October 30, 15"
Constants
The value of a constant does not change during program execution. Constants are
simple scal ar v alue s that you ca n use w ithi n exp res sion s and fun ctio ns . They incl ude
integers, r eal nu mber s , tim e an d dat e valu es , b oole a n valu es, string values, and lists.
6Chapter 1 ColdFusion Expressions: Operands, Operators and Other Constructs
Variables
V ariables are the most frequ ently used oper ands. Variable values can be set and reset,
and passed as attributes to CFML tags and JRun servlets. They can be passed as
parameters to functions, and can replace most const ants.
For a list of the variables associated with ColdFusion, see the CFML Quick Reference.
Variable naming conventions
When naming ColdFusion variables and form fields, keep these guideline s in mind:
•Variable names must begin with a letter, which can be followed by any number of
letters or numbers or the underscore character.
•Variable names must be one word.
•Do not use spaces in variable names.
•Use descriptive names not abbreviations.
•Queries and variables cannot have the same name in a ColdFusion application
page.
•Although ColdFusion variables are not case-sensitive, keep capitalization
consistent in order to keep your code consistent.
•When writing queries and forms, match your form fi eld names with the
corresponding database field name.
•In some cases, you must put a pounds signs around a variable name to allow
ColdFusion to distinguish it from string or HTML text, and to insert its value as
opposed to its name. For more information, see “Pound Signs” on page 20.
ColdFusion variable types
The following table describes the types of variables you can use in a ColdFusion
application page.
Variable Type Description
Query ResultResults of a database query can be u sed as dyn am ic p ara me ters .
For example, if you create a query named LookupUser that finds
the ID for a given u se r name, you can use th is ID in another query
or in a call to cfoutput.
Local VariableThe default scope for variables of any type created with the cfset
and cfparam tags. For example,
A to 5. This variable is available only on the application page
where it is created and any included pages.
URL ParameterParam eters app ended to a URL af ter the ap plicatio n page name in
the format variablename = value. URL parameters are stored in
structures. For more information, see “Vari ables stored in
structures” on page 12.
<cfset A = 5> sets the variable
Variables7
Variable Type Description
Form FieldThe most common way of passing parameters to a page. When a
user enters data in a form field, a parameter with the name of the
form field is passed to the action page. Form fields are stored in
structures. For more information, see “Vari ables stored in
structures” on page 12.
ClientVariables associated with a particular client. Lets you maintain
state as a user m ove s fro m page to page in an ap plication. Stored
in the system registry by default, but you can also store them in a
cookie or in a database.
Client variables are part of the ColdFusion Web Application
Framework. For more information, see Developing Cold Fus io n Applications.
ServerVariables associated with the current Web server. Available to all
ColdFusion applications until the ColdFusion server is shut down.
This server scope lets you define variables that all your
ColdFusion application pages can reference.
Server variables are stored in structu res . For more informa t io n,
see “Variables stored in structures ” on page 12.
For information on locking server variables, see the description of
cflock on page 174.
SessionVariables tied to an individual client that persist for as long as that
Client ID maint ains a ses sion. Session variables , like curre nt client
variables, require a client name and are available only to that one
Client ID.
Unlike client varia bles, sessi on vari ables ar e stored in the ser ver’s
memory and can be set to time-out after a precise period of
inactivity.
Session variables are stored in structures. For more information,
see “Variables stored in structures ” on page 12.
Session variables should be locked when accessed. For
inform ation, see the description of cflock on page 174.
Session variables are part of the ColdFusion Web Application
Framework. This means that they are used in the context of an
Application.cfm page. For more information, see Developing
ColdFusion Applications and the descr ipti on of cfapplication on
page 37.
8Chapter 1 ColdFusion Expressions: Operands, Operators and Other Constructs
Variable Type Description
ApplicationV ariab les ti ed to a n appl ication a s defi ned in the CFAPPLICATION
NAME attribute, typically used in the
Application.cfm file.
Application variables work only if an application name is defined.
Application variables are stored in structures. For more
information, see “Variables stored in structures” on page 12.
Application variables should be locked when accessed. For
inform ation, see the description of cflock on page 174.
Application variables are part of the ColdFusion Web Application
Framework. This means that they are used in the context of an
Application.cfm page. For more information, see Developing
ColdFusion Applications and the descr ipti on of cfapplication on
page 37.
RequestVariables storing data that pertains to the processing of a request
to a single page.
Request variables are convenient for storing data in a structure,
carried through ne sted t ags, suc h as Custo m Tags, and process ed
at once.
Request variables are stored in structures. For more information,
see “Variables stored in structures ” on page 12.
CallerVariable that lets you call and use variables from the calling
template in a ColdFusion custom tag.
HTTP CookiesVariables stored in the browser. Available every time the browser
makes a page request. You can create cookie variables with the
cfcookie tag.
FileRead-only variables. Created when a cffile action = "upload"
operation is executed.
CGI Environment Every page request has several environment variables sent to it
that relate to the context in which it was requested. The variables
available depend on the browser and server software. For a list of
the commonly used CGI variables, see “CGI Environment
Variables” on page 13.
Note: CGI environment variables are created even when you are
using a Web server that supports a server API.
Qualifying, or scoping, variable references
ColdFusion distinguishes between identically named parameters from different
sources by using a different prefix for each source. Specifying a variable’s source is
known as “scoping”the variable. For example, to specify a variable called S tate that is
passed in a form submission, you would reference it as
variable named State passed in a URL, you would reference it as
Form.State. To specify a
URL.State.
Variables9
Although you are not required to use the scope prefix unless two variables in
different scopes have the same name, it is recommended for readability and
processing speed that you use prefixes. For example, the variable
clearer than a variable called simply
lastname.
Form.lastname is
Tip
Specify the variable’s scope prefix for all Application, Session, Server, and Request
variables.
Many CFML tags, such as
cferror and cfftp, have variables associated with them.
Typically, these variables use the tag name as the prefix. For a list of the variables, see
the Quick Reference to CFML.
Note
Any variable that can be created using
cfset can also be created with an assignment
statement in cfscript.
Scopes and variables
The following table lists the types of variable scopes, and shows how you refer to
them in your code. In addition to these scopes, there are a number of ColdFusion
data structures that provide information about the results of a tag or operation. For
information on special variables, see the CFML Quic k Reference and the
documentation of the individual CFML tags that return these variables.
PrefixRequiredAvailabilityComment
Variables
(Local)
NoCannot be accessed by a custom tag
called by the page or by an action
page that di ffers f rom a form p age that
creates the variables
Created by the
by using a Variables prefix or no
prefix
cfset or cfparam tag
FormNoCan be used on the action page of a
form; cannot be used on a form page
that is not also the action page
URLNoThe target page of a URLContains the parameters passed in
AttributesYesOn the custom tag page onlyContains the values passed in the
CallerNo in calling
page.
Y es in custom
tag page.
As normal loc al v ari abl es o n t he p a ge
calling the custom tag. Available on
the custom tag page by using the
Caller scope prefix.
Created by the
name attribute. Contains the values
form or cfform tag
of data tags (such as input) in the
form body when the form is
submitted.
the URL query string that ac cesses a
page
custom tag ’s attributes by the calling
page to a custom tag page
Created in a custom tag page
or
cfparam tag by using a Caller
cfset
prefix. Created as local variables on
the calling tag page.
10Chapter 1 ColdFusion Expressions: Operands, Operators and Other Constructs
PrefixRequiredAvailabilityComment
RequestYesOn the cr ea tin g page and in a ny t a gs ,
including nested tags, called after the
variable is created
CGINoOn any page; values are specific to
the latest browser request
CookieNoFor one client, in one or many
applications and pages, over multiple
browser sessions
ClientNoFor one client in one application over
multiple browser sessions
SessionYesFor one client in one application and
one browser session
Application YesFor multiple clients in one application
over multiple browser sessions
ServerYesOn any page on the ColdFusion
server
Performance and scoping
Created by the
cfset or cfparam tag
by using a Request prefix
Created by the W eb server . Con tains
the server environment variables
that result from the browser request.
Created by the
Created by the
cfcookie tag
cfset or cfparam tag
by using a Client prefix
Created by the
cfset or cfparam tag
by using a Session prefix
Created by the
cfset or cfparam tag
by using an Application prefix
Created by the cfset or cfparam tag
by using a Server prefix
You can improve performance by qualifying variables with the proper scope. Adding
variable scopes improves processing speed, but the trade-off is that it may reduce the
ease of code reuse.
In the following example, both forms of the fullname variable are permitted.
However, the example that includes a scoping prefix will be evaluated more quickly
than the unscoped ex am p l e:
<cfoutput>
#Client.fullname#
#fullname#
</cfoutput>
When a variable does not have a scope prefix, ColdFusion searches for it in the
following sequence:
1Local variables created using cfset and cfquery
2CGI
3File
4URL
5Form
6Cookie
7Client
Variables11
Note
ColdFusion does not attempt to automatically find Application, Session, Server,
Request, or CFML tag variables (except File variables). You must use prefixes with
these variables.
The following scopes are exposed as ColdFusion structures:
•Form
•URL
•Attributes
•Request
•CGI
•Cookie
•Session
•Application
Note
Variables on one application page can be used on any other appl ication page that is
included with the
cfinclude tag. Variables on the included page can also be
accessed by the including page.
Variables across application pages
Most ColdFusion variables apply only to a single application page. However, several
types of variables can be used across multiple application p ages:
•Client variables store identifying information about an individual client.
Client variables hold long-term information about an individual client. You can
store them in the system registry, a database, or a cookie named for the
application.
•Server variables are valid for all ColdFusion applications on a server.
Server variables store information (typically read-only) that does not change
often and can be shared across users and ColdFusion applications.
•Session variabl e s are valid for as long as an individual Client ID maintains a
session.
Session variables are useful for storing short-term information needed for a
single site visit or set of requests. They are specific to individual users.
•Application va riables are valid for an application.
Application variables are available to individual, specified appli cations and to all
users of that ap plicatio n wh o acces s the C oldF usi on se rver. They are stored in the
server’s memory and can be set to time out.
•Cal ler variables are valid for ColdFusion custom tags.
Caller variables are available for passing information among application pages of
a ColdFusion custom tag.
12Chapter 1 ColdFusion Expressions: Operands, Operators and Other Constructs
Note
When variables are available to several application pages, keep track of your variable
names. For more information, see “Variable naming conventions” on page 6.
For information on setting up client state management using the clientManagement
attribute in the
cfapplication tag, see the description of cfapplication on page 37.
For information about using Application, Client, and Session variables, see
Developing ColdFusion Applications.
Variables stored in structures
As of ColdFusion 5, Form, Application, Session, Server, Request, and URL variables
are stored in structures. Thus, you can reference all of the fields taken from a form as
a structure, all parameters passed in a URL as a structure, and so forth.
You can access structures using any of the ColdFusion structure functions in the
form structname.key, where each key represents a field name of a form or a variable
name of a specific type. Because ColdFusion creates these structures whenever these
variables are used, conversion to WDDX is straightforward.
<input type = "Text" name = "Title"><br>
<input type = "Text" name = "URL"><br>
<textarea name = "teaser" rows = "3" cols = "40"></textarea>
<br>
<input type = "Submit" name = "submit" value = "Submit">
</form>
</cfoutput>
Note
Do not use
StructClear to clear session and application variables. This can cause
the loss of SessionID, CFID, CFTOKEN, and application variables. To prevent this
loss, store session data in session.foo.* and then clear session.foo, and store
application data in application.foo.* and then clear application.foo.
CGI Environment Variables13
CGI Environment Variables
When a browser makes a request to a server, environment variables are created by
the Web server and by the browser. In ColdFusion, these variables are referred to as
CGI environment variables and they use the "CGI" prefix (even if your server uses a
server API instead of CGI to communicate with the ColdFusion Server).
Environme nt variables contain da ta about the transaction between the browser and
the server, such as the IP Address, browser type, and authenticated username. You
can reference CGI environment variables for a given page request anywhere in the
page. CGI variables are read-only.
Note
The environment variables available to your applications depend on the browser and
server s oftware.
Testing for CGI variables
Because all CGI variables are not supported by all browsers, ColdFusion always
returns TRUE when testing for the existence of a CGI variable, even if the variable is
not supported by the client browser. To work around this, test for an empty string to
determine if the CGI variable is available.
<cfif CGI.varname IS NOT "">
CGI variable exists
<cfelse>
CGI variable does not exist
</cfif>
CGI server variables
The following table describes common CGI environment variables created by a
server (not all of these will be available with every server):
CGI Server VariableDescription
SERVER_SOFTWAREName and version of the information server software
SERVER_NAMEServer’s hostname, DNS alias, or IP address as it appears
answering the request (and running the gateway). Format:
name/version.
in self-referencing URLs.
GATEWAY_INTERFACE Revision of the CGI specification with which this server
SERVER_PROTOCOLName and revision of the information protocol this request
SERVER_PORTPort number to which the request was sent.
complies. Format: CGI/revision.
came in with. Format: protocol/revision.
14Chapter 1 ColdFusion Expressions: Operands, Operators and Other Constructs
CGI Server VariableDescription
REQUEST_METHODMethod with which the re quest wa s made. For HTTP, this is
Get, Head, Post, and so on.
PATH_INFOExtra path information, as given by the client. Scripts can
be accessed by their virtual pathname, followed by extra
information at the end of this path. The extra information is
sent as PATH_INFO.
PATH_TRANSLATEDTranslated version of PATH_INFO after any
virtual-to-physical mapping.
SCRIPT_NAMEVirtual path to the script being executed; used for
self-referencing URLs.
QUERY_STRINGQuery information that follows the ? in the URL that
referenced this script.
REMOTE_HOSTHostname making the request. If the server does not have
this information, it sets REMOTE_ADDR and does not set
REMOTE_HOST.
REMOTE_ADDRIP address of the remote host making the request.
AUTH_TYPEIf the server supports user authentication, and the script is
REMOTE_USER
AUTH_USER
REMOTE_IDENTIf the HTTP server supports RFC 931 identification, this
CONTENT_TYPEFor queries that have attached information, such as HTTP
CONTENT_LENGTHLength of the content as given by the client.
CGI client var ia ble s
The following table describes common CGI environment variables that are created
by the browser and passed in the request header:
CGI Client Varia bleDescription
protected, the pr otocol-spec ific authentica tion method us ed
to validate the user.
If the server supports user authentication, and the script is
protected, the username the user has authenticated as.
(Also available as AUTH_USER.)
variable is set to the remote username retrieved from the
server. Use this variable for logging only.
POST and PUT, this is the content type of the data.
HTTP_REFERERThe referring document that linked to or submitted
form data.
CGI Environment Variables15
CGI Client Varia bleDescription
HTTP_USER_AGENTThe browser that the client is currently using to send
the request. Format: software/version library/version.
HTTP_IF_MODIFIED_SINCE The last time the page was modified. The browser
determines whether to set this variable, usually in
response to the server having sent the
LAST_MODIFIED HTTP header. It can be used to
take advantage of browser-side caching.
CGI client certificate variables
ColdFusion makes available the following client certificate data. These var iables are
available when running Microsoft IIS 4.0 or Netscape Enterprise under SSL if your
Web server is configured to accept client certificates.
CGI Client Certificate
Variable
CERT_SUBJECTClient-specific information provided by the web server.
CERT_ISSUERInformation about the authority that provided the client
CLIENT_CERT_ENCODED The entire client certificate binary, base-64 encoded.
Description
This data typically includes the client’s name, e-mail
address, etc. For example:
O = "V eriSign, Inc.", O U = V eriSign T rus t Network, OU =
"www.verisign.com/repository/RPA Incorp. by
Ref.,LIAB.LTD(c)98", OU = Persona Not Validated, OU
= Digital ID Cla ss 1 - Microsof t, CN = Matthew Lun d, E =
mlund@macromedia.com
certifi cate. For example:
O = "V eriSign, Inc.", O U = V eriSign T rus t Network, OU =
"www.verisign.com/repository/RPA Incorp. By
Ref.,LIAB.LTD(c)98", CN = VeriSign Class 1 CA
Individual Subscribe r-Pers ona Not Validated
This data is typically of in terest to d evelopers integrati ng
with other software that uses client certificates.
16Chapter 1 ColdFusion Expressions: Operands, Operators and Other Constructs
Operators
Operators combine subexpressions to create complex expressions. Operators act on
the operands. The general syntax for using operators is:
Expression Operator Expression
ColdFusion has four types of operators:
•Arithmetic
•Boolean
•Decision (or comparison)
•String
Functions also can be viewed as operators because they act on operands.
Arithmetic operators
The arithmetic operators are shown in the following table.
Operator Description
+ - * /The basic arithmetic ope rato rs: add iti on, subtraction, multipli ca tion, and
division. In division, the right operand cannot be zero.
+ -Unary arithmetic operators for setting the sign of a number.
MODReturns the remainder (modulus) after a number is divided by a divisor.
The result has the same sign as the divisor. The right operand cannot be
zero. For example, 11 MOD 4 is 3.
\Divide an integer by another integer. Use the \ (trailing slash) to separate
the integers. The right operand cannot be zero. For example, 9 \ 4 is 2.
^Returns the result of a number raised to a power (exponent). Use the ^
(caret) to sepa rate the num be r fro m t he p ow er. The left operand can no t be
zero. For example, 2 ^ 3 is 8.
Boolean operators
Boolean, or logical, operators perform logical connective and negation operations.
The operands of Boolean operators are Boolean (TRUE/FALSE) values.
Operator Description
NOTReverses the value of an argument. For example, NOT TRUE is FALSE
and vice versa.
ANDReturns TRUE if both argume nt s ar e TRU E; re turn s FALSE otherwise. For
example, TRUE AND TRUE is TRUE, but TRUE AND FAL SE is FALSE.
ORReturns TRUE if any of the arg um ents is TRUE; returns FALSE otherwise.
For example, TRUE OR FALSE is TRUE, but F ALSE OR FALSE is FALSE.
Operators17
Operator Description
XORExclusive or —either, or, but not both. Returns TRUE if the truth values of
both arguments are different; returns FALSE otherwise. For example,
TRUE XOR TRUE is FALSE, but TRUE XOR FALSE is TRUE.
EQVEquivalence both true or both false. The EQV operator is the opposite of
the XOR operator. For example, TRUE EQV TRUE is TRUE, but TRUE
EQV FALSE is FALSE.
IMPImplication. A IM P B is the truth value o f the logic al st atement “If A Then B.”
A IMP B is FALSE only when A is TRUE and B is FALSE.
Decision operators
ColdFusion’s decision, or comparison, operators produce a Boolean TRUE/FALSE
result. The decision operators are shown in the following table.
OperatorDescription
ISPerforms a case-insensitive com p a ris on of two
values. Returns true if the values are identical.
IS NOTOpposite of is.
CONTAINSDetermines whether the value on the left is
contained in the va lue on the right. Returns true if
it is.
DOES NOT CONTAINOppos ite of contains.
GREA TER THANDetermines whethe r the value on the lef t is grea ter
than the value on the right. Returns true if it is.
LESS THANOpposite of greater than.
GREA TER THAN OR EQUAL TO Determ ines whethe r the value on the lef t is grea ter
than or equal to the value on the right. Returns
true if it is.
LESS THAN OR EQUAL TODetermines whether the value on the left is less
than or equal to the value on the right. Returns
true if it is.
Shorthand notation for decision operators
You can replace some decision operators with shorthand notations to make your
CFML more compact, as shown in the following table.
OperatorAlternative name(s)
ISEQUAL, EQ
IS NOTNOT EQUAL, NEQ
18Chapter 1 ColdFusion Expressions: Operands, Operators and Other Constructs
OperatorAlternative name(s)
GREATER THANGT
LESS THANLT
GREATER THAN OR EQUAL TO GTE, GE
LESS THAN OR EQUAL TOLTE, LE
String operators
There is one string operator, which is the concatenation ope rator.
OperatorDescription
&Concatenates strings.
Operator precedence
The order of precedence controls the order in which operators on the same line are
evaluated. The order of precedence is shown below:
Unary +, Unary ^
*, /
\
MOD
+, &
EQ, NEQ, LT, LTE, GT, GTE, CONTAINS, DOES NOT CONTAIN
NOT
AND
OR
XOR
EQV
IMP
To enforce a non-standard order of evalua tion, you must parenthesi ze expressions.
For example:
•6 - 3 * 2 is equal to 0
•(6 - 3) * 2 is equal to 6
Parenthesized expressions can be nested. When in doubt about the order in which
operators in an expression will be evaluated, use parentheses.
Functions as Operators19
Functions as Operators
Functions are a form of operator. Because ColdFusion functions return basic objects,
such as numbers, strings, Boolean values, date-and-time objects, lists, arrays,
structures, queries, and COM objects, function results can be used as operands.
The following sections des cribe:
•function syntax
•optional function arguments
Function syntax
The following table shows function syntax and usage guidelines.
UsageExample
No arguments
Basic format
Nested functions
Multiple arguments
String arguments
Arguments that are expressions
For more information on how to insert functions in expressions, see “Pound Signs”
on page 20.
Optional function arguments
Functions can take optional arguments after their required arguments. If omitted, all
optional arguments default to a predefined value. For example:
The differ enc e in t he r esu lts is becau se th e Replace function ta kes a n opti onal fou rth
argument that specifies the scope of replacement. The default value is "ONE" which
explains why only the first occurrence of "Foo" was replaced with "Boo". In the
second example, a fourth argument causes the function to re pla ce all occurrences of
"Foo" with "Boo".
Function()
Function(Data)
Function1(Function2(Data))
Function(data1, data2, data3)
Function(’This is a demo’)
Function("This is a demo")
Function1(X*Y, Function2("Text"))
20Chapter 1 ColdFusion Expressions: Operands, Operators and Other Constructs
Pound Signs
Pound signs (#) have a sp ecial meani ng in CFML. Co ldFu sion tr eats te xt delim ited b y
pound signs diffe re ntly from pla in te xt. Wh en C oldF usion pr ocesses a n expression, it
replaces the text of the expression and the two pound signs around it with its
resulting value.
For example, to output the current value of a variable named
you delimit the variable name with pound signs:
<cfoutput>Value is #Form.MyFormVariable#</cfoutput>
In the exampl e ab ove, the expression #Form.MyFormVariable# is replaced with
whatever value has been assigned to it.
Follow these guidelines when using pound signs:
•Use pound signs to distinguish expressions from plain text.
•When expressions are evaluated, the resulting value is substituted for the
expression text.
•Use pound signs only where necessary. See “Pound signs in general expressions”
on page 23 before using them.
The following sections provide more details on how pound signs should be used in
CFML.
Pound signs in cfoutput tags
Expressions that contain one variable or a single function can be used freely inside
cfoutput tags as long as they are enclosed in pound signs.
<cfoutput>
Value is #Form.MyTextField#
</cfoutput>
Form.MyFormVariable,
<cfoutput>
The name is #FirstName# #LastName#.
</cfoutput>
<cfoutput>
Cos(0) is #Cos(0)#
</cfoutput>
If pounds are omitted, the expression text rather than the expression value appears
in the output generated by the
Two expressions inside pound signs can be adjacent to one another, as in this
example:
<cfoutput>
"Mo" and "nk" is #Left("Moon", 2)# #Mid("Monkey", 3, 2)#
</cfoutput>
cfoutput statement.
Pound Signs21
Complex expressions and cfoutput tags
Complex expressions, which contain more that one vari able or function, cannot be
inserted inside
<cfoutput>1 + 1 is #1 + 1#</cfoutput>
cfoutput tags. The following example produces an error:
To insert the value of a complex expression in the output generated by a cfoutput
statement, use
variable inside the
<cfset Result = 1 + 1>
<cfoutput>1 + 1 is #Result#</cfoutput>
cfset to set a variable to the value of the expression, and use the
cfoutput statement, as shown below:
Pound signs in strings
Expressions that contain one variable or function can be used inside strings if they
are enclosed in pound signs.
<cfset TheString = "Value is #Form.MyTextField#">
<cfset TheString = "The name is #FirstName# #LastName#.">
<cfset TheString = "Cos(0) is #Cos(0)#">
ColdFusion automatically replaces the expression text with the value of the variable
or the value returned by the function. For example, the following pairs of
statements produce the same result:
If pound signs are omitted, the expression text, rather than the expression value,
appears in the string. For example, the following pairs of
the same result:
As with the cfoutput statement, in strings, two expressions can be adjacent to each
other, as in the following example:
<cfset TheString = "Monk is #Left("Moon", 2)##Mid("Monkey", 3, 2)#">
The double quotes around "Moon" and "Monkey" need not be escaped (as in
""Moon"" and ""Monkey""). This is because the text between the pound signs is
treated as an expression, it is evaluated first before its value is inserted inside the
string.
Inserting complex expressions in strings
cfset
cfset statements produce
Complex expressions that have one or more operators cannot be used inside strings.
The following example produces an error:
<cfset TheString = "1 + 1 is #1 + 1#">
22Chapter 1 ColdFusion Expressions: Operands, Operators and Other Constructs
To insert the value of a complex expres sion inside a string, do one of the following:
•Use
cfset to set a variable to the value of the expression and use that variable
inside the string
•Use the string concatenation operator
Both techniques are shown in the following example;
<cfset Result = 1 + 1>
<cfset TheString = "1 + 1 is #Result#">
<cfset TheString = "1 + 1 is " & (1 + 1)>
To insert the pound character in a string, use two pound signs, as shown below:
<cfset TheString = "This is a pound sign ##.">
Pound signs in tag attribute values
The rule s for using pound signs inside strings also apply to the use of pound si gns
inside tag attribute values. The following example demonstrates the point:
<cfcookie name = "TestCookie"
value = "The value is #CookieValue#">
If the value of a tag attribute is a variable, function, or array element, use the
following syntax:
<cfcookie name = "TestCookie"
value = #CookieValue#>
<cfcookie name = "TestCookie"
value = #CookieValueArray[Index]#>
This usage is more efficient than value = "#CookieValue#".
Pound signs in custom tag attribute values
The rules described in the previous section apply to custom tags. However, custom
tags can also h ave c omplex o bjects pass ed as a ttribute value s, w hich C oldFu sion t ags
cannot. Complex objects, such as arrays, structures, queries, and COM objects, are
passed to custom tags surrounded by pound signs (#). For example:
<cfset myinfo = StructNew()>
<CF_FillInMyInfo info = #myinfo# name = "pete" size = "22">
Nested pound signs
There are few cases in which pound signs can be nested in an expression. The
following example shows a valid use of nested pound signs:
<cfset Sentence = "The length of the full name is
#Len("#FirstName# #LastName#")#">
Pound signs must be nested so that the values of the variables FirstName and
LastName are inserted in the string whose length the
Len function calculates. Often,
Pound Signs23
the existence of nested pounds implies a complex expression. For example, the
above CFML code could be rewritten to improve its readability:
<cfset FullName = "#FirstName# #LastName#">
<cfset Sentence = "The length of the full name
is #Len(FullName)#">
A common mistake is to put pound signs around the arguments of functions, as in:
24Chapter 1 ColdFusion Expressions: Operands, Operators and Other Constructs
Chapter 2
ColdFusion Tags
This chapter describes the ColdFusion Markup Language (CFML) tags. The
introduction contains an alphabetical summary of ColdFusion tags, a list of new tags
in ColdFusion 5, and a list of tags by category. The rest of this chapter describes each
tag in detail.
Contents
•Alphabetical List of ColdFusion Tags.......................................................................26
•New tags in ColdFusion 5.........................................................................................30
ColdFusion Markup Language (CFML) consists of a set of tags you use in ColdFusion
pages to interact with data sources, manipulate data, and display output. Using
CFML tags is very simple; tag syntax is much like HTML element syntax.
The following table provides brief descriptions of the CFML tags.
CFML TagCategoryDescription
cfabort
cfapplet
cfapplication
cfassociate
cfauthenticate
cfbreak
cfcache
cfcol
cfcollection
cfcontent
cfcookie
cfdirectory
cfdump
cferror
cfexecute
cfexit
cffile
Flow-controlStops processing of a ColdFusion page at
the tag location.
FormEmbeds Java applets in a cfform tag.
Web app.
framework
Web app.
framework
Web app.
framework
Defines application name; activates client
variables.
Enables subtag data to be saved with a
base tag.
Authenticates a user and sets the security
context for an application.
Flow-controlBreaks out of a CFML looping construct.
Caches ColdFusion pages.
Data outputDefines table column header, width,
alignment, and text .
ExtensibilityCreates and administers Verity collections.
Data outputDefines the content ty pe and , op tionally, the
filename of a file to be downloaded by the
current page.
Variable
Defines and sets cookie variables.
manipulation
File
management
Variable
Performs typical directory-handling tasks
from within a ColdFusion application.
Outputs variables for debugging purposes.
manipulation
Exception
handling,
Displays customized HTML error pages
when errors occur.
web app.
framework
Flow-controlExecutes a develop er-specif ied process on
the server computer.
Flow-controlAborts pr ocessing of an executing CFML
custom tag.
File
management
Performs typical file-handling tasks from
within a ColdFusion app lic ati on.
Alphabetical List of ColdFusion Tags27
CFML TagCategoryDescription
cfflush
cfform
Data outputFlushes currently availa ble dat a to th e clien t.
FormBuilds an input form; performs client-side
input validation.
cfftp
Internet
Permits FTP file operations.
protocol
cfgraph
cfgraphdata
cfgrid
Data outputDisplays a graphical representation of data.
Data outputSpecifies a data point to be displayed by a
cfgraph tag.
FormUsed in cfform to create a grid control for
tabular data.
cfgridcolumn
cfgridrow
cfgridupdate
FormUsed in cfform to define the columns used
cfgrid.
in a
FormUsed with cfgrid to define a grid row.
FormPerforms updates directly to ODBC data
source from edited grid data.
cfheader
cfhtmlhead
cfhttp
Data outputGenerates HTTP headers.
Internet
protocol
Internet
protocol
Writes text, including HTML, to the HEAD
section of a page.
Performs GET and POST to upload files or
post a form, cookie, query, or CGI variable
directly to a specified server.
cfhttpparam
cfif/cfelseif/cfelse
cfimpersonate
cfinclude
cfindex
Internet
protocol
Used with cfhttp to specify parameters
necessary for a
cfhttp POST operation.
Flow-c ontrolCreate IF-THEN-ELSE constructs.
Web app.
framework
Impersonates a user that is defined in an
Advanced Security context.
Flow-controlEmbeds references to ColdFusion pages.
Exception
Creates Verity search indexes.
handling
cfinput
FormUsed in cfform to create input elements
such as radio buttons, checkboxes, and text
entry boxes.
cfinsert
cfldap
DatabaseInserts records in an ODBC data source.
Internet
Provides access to LDAP directory servers.
protocol
cflocation
cflock
cflog
Flow-controlOpens a ColdFusion page or HTML file .
Web app.
framework
Ensures data int egri ty and sy nc hro niz es th e
execution of CFML code.
OtherWrites a message to a log file.
28Chapter 2 ColdFusion Tags
CFML TagCategoryDescription
cfloop
Flow-controlRepeats a se t o f i nst ruc tio ns based on a se t
of conditions.
cfmail
Internet
Assembles and posts an e-mail message.
protocol
cfmailparam
cfmodule
cfobject
cfoutput
Internet
protocol
Web app.
framework
extensibility,
Java
Attaches a file o r adds a he ader t o a n e-m ail
message.
Invokes a custom tag for u se in ColdFusion
application pages.
Creates and use s COM, C O RBA, and J AV A
objects.
Data outputDisplays output of database query or other
operation.
cfparam
Variable
Defines a parameter and its default value.
manipulation
cfpop
cfprocessingdirective
Internet
protocol
Retrieves messages from a POP mail
server.
Data outputSuppresses extraneous white space and
other output.
cfprocparam
DatabaseSpec ifi es p a ram eter information for a s tored
procedure.
cfprocresult
DatabaseSpecifies a result set name that ColdFusion
tags use to access the result set from a
stored procedure.
cfquery
cfqueryparam
cfregistry
DatabasePasses SQL to a database.
DatabaseChecks the data type of a query parameter.
OtherReads, writes, and deletes keys and values
in the system registry.
cfreport
Exception
Embeds a C rystal Reports report.
handling
cfrethrow
Exception
Rethrows the currently active exception.
handling
cfsavecontent
cfschedule
cfscript
Variable
manipulation
Variable
manipulation
Web app.
Saves generated content inside the tag
body in a variable.
Schedules page execution, optionally
produces static pages.
Encloses a set of cfscript statements.
framework
cfsearch
Exception
handling
Executes searches against data indexed in
Verity collections using
cfindex.
Alphabetical List of ColdFusion Tags29
CFML TagCategoryDescription
cfselect
FormUsed in cfform to create a drop-down list
box form element.
cfservlet
extensibility,
Executes a Java servlet on a JRun engine.
Java
cfservletparam
cfset
extensibility,
Java
Variable
Passes data to a Jav a se rvle t. A chi ld t ag of
cfservlet.
Defines a variable.
manipulation
cfsetting
cfsilent
OtherDefines and controls ColdFusion settings.
Data outputSuppresses output produced by CFML
<H1>cfabort Example</H1>
<P>
<H3>Example A: Let the instruction complete itself</H3>
<!--- first, set a variable --->
<cfset myVariable = 3>
<!--- now, perform a loop that increments this value --->
<cfloop from = "1" to = "4" index = "Counter">
<cfset myVariable = myVariable + 1>
</cfloop>
34Chapter 2 ColdFusion Tags
<cfoutput>
<P>The value of myVariable after incrementing through the loop
#Counter# times is: #myVariable#
</cfoutput>
<!--- reset the variable and show the use of cfabort --->
<H3>Example B: Use cfabort to halt the instruction</H3>
<cfset myVariable = 3>
<!--- now, perform a loop that increments this value --->
<cfloop from = "1" to = "4" index = "Counter">
<!--- on the second time through the loop, cfabort --->
<cfif Counter is 2>
<cfabort>
<!--- the processing is stopped, and subsequent operations
are not carried out by the CFAS --->
<cfelse>
<cfset myVariable = myVariable + 1>
</cfif>
</cfloop>
<cfoutput>
<P>The value of myVariable after incrementing through the loop
#counter# times is: #myVariable#
</cfoutput>
</body>
</html>
Alphabetical List of ColdFusion Tags35
cfapplet
DescriptionUsed in a cfform tag, cfapplet lets you reference custom Java applets that you have
registered using the Co ldFu sion Admi nistr ato r.
To register a Java applet, open the Cold Fusion Administrator and click Applets.
CategoryForms tags
Syntax
<cfapplet appletSource = "applet_name"
name = "form_variable_name"
height = "height_in_pixels"
width = "width_in_pixels"
vSpace = "space_above_and_below_in_pixels"
hSpace = "space_on_each_side_in_pixels"
align = "Left" or "Right" or "Bottom" or "Top" or "TextTop" or "Middle"
or "AbsMiddle" or "Baseline" or "AbsBottom"
notSupported = "message_to_display_for_nonJava_browser"
param_1 = "applet_parameter_name"
param_2 = "applet_parameter_name"
param_n = "applet_parameter_name">
See alsocfform, cfobject, cfservlet
Attributes
AttributeDescription
appletSourceRequired. The name of the registered applet.
nameRequired. The form variable name for the applet.
heightOptional. The height of the applet, in pixels.
widthOptional. The width of the applet, in pixels.
vSpaceOptional. Space above and below applet, in pixels.
hSpaceOptional. Space on each side of the applet, in pixels.
alignOptional. Alignment. Options are:
Left
•
• Right
• Bottom
• Top
• TextTop
• Middle
• AbsMiddle
• Baseline
• AbsBottom
36Chapter 2 ColdFusion Tags
AttributeDescription
notSupportedOptio nal . The tex t to d is pla y i f a page containing a Java appl et-b as ed
cfform control is opened by a browser that does not support Java or
has Java support disabled. For example:
notSupported = "<B>Browser must support Java to view
ColdFusion Java Applets</B>"
By default, if no message is specified, the following message
displays:
<B>Browser must support Java to <BR>
view ColdFusion Java Applets!</B>
paramnOptional. The name of a registered parameter for the applet. Specify
a parameter only to ov erride p aram eter va lues alread y defin ed for the
applet in the ColdFusion Adminis trat or.
UsageSince Java applets must be pre-registered, the cfapplet tag can be very simple,
taking the default parameter values as they were registered in the ColdFusion
Administrator. You can also override parameters by invoking them in the cfapplet
tag.
Example
<!--- This example shows the use of cfapplet --->
<html>
<head>
<title>cfapplet Example</title>
</head>
<body>
<H3>cfapplet Example</H3>
<P>Used in a cfform, cfapplet allows you to reference
custom Java applets that have been previously registered
using the ColdFusion Administrator.
<P>To register a Java applet, open the ColdFusion Administrator
and click the "Applets" link under the "extensions" section.
<P>This example applet copies text that you type into
a form. Type some text, and then click "copy" to see
the copied text.
<cfform action = "copytext.cfm">
<cfapplet appletsource = "copytext" name = "copytext">
</cfform>
</body>
</html>
Alphabetical List of ColdFusion Tags37
cfapplication
DescriptionDefines scoping for a ColdFusion application, enables or disables storing client
variables, and specifies a client variable storage mechanism. By default, client
variables are disabled. Also, enables session variables and sets timeouts for session
and application variables. Session and application variables are stored in memory.
CategoryWeb application framework tags
Syntax
<cfapplication name = "application_name"
clientManagement = "Yes" or "No"
clientStorage = "datasource_name" or "Registry"
or "Cookie"
setClientCookies = "Yes" or "No"
sessionManagement = "Yes" or "No"
sessionTimeout = #CreateTimeSpan(days, hours,
minutes, seconds)#
applicationTimeout = #CreateTimeSpan(days, hours,
minutes, seconds)#
setDomainCookies = "Yes" or "No">
See alsocfassociate, cfauthenticate, cferror, cflock, cfmodule
Attributes
AttributeDescription
nameThe name of your application. This name can be up to 64
characters long.
Required for application and session variables, optional for
client variables.
clientManagementOptional. Yes or No. Enables client variables. Default is No.
clientStorageOptional. Specifies how ColdFusion stores client variables:
datasourcenameStore clien t vari abl es in the sp eci fied
•
ODBC or native data source. To use this option, you must
create a client variable storage repository using the
Variables page of the ColdFusion Administrator.
registryStore client variables in the system registry
•
(default).
cookieStore client variables on the client computer in a
•
cookie. Storing client data in a cookie is scalable for large
numbers of clien ts , but with this s torage m ethod, if the c lient
turns off co ok ies i n th e brows er, client variables do no t w o rk.
setClientCookiesOptional. Yes or No. Yes enables client cookies. Default is
Yes.
If you set this attribute to "No", ColdFusion does not
automatically send the CFID and CFTOKEN cookies to the
client browser; you must manually code CFID and CFTOKEN
on the URL for every page that uses Session or Client
variables.
38Chapter 2 ColdFusion Tags
AttributeDescription
sessionManagement Optional. Yes or No. Yes enables session variables. Default is
No.
sessionTimeoutOptional. Enter the CreateTimeSpan function and values in
days, hours, minutes, and seconds, separated by commas, to
specify the lifespan of session variables. The default value is
specified in the Variables page of the ColdFusion
Administrator.
applicationTimeoutOptional. Enter the CreateTimeSpan function and values in
days, hours, minutes, and seconds, separated by commas, to
specify the lifespan of application variables. The default value
is specified in the Variables page of the ColdFusion
Administrator.
setDomainCookie sOptional. Yes or No. Sets the CFID and CFTOKEN cookies for
a domain, not just a single host. Applications that are running
on clusters must set this value to Yes. The default is No.
UsageThe cfapplication tag is typically used in the Application.cfm file to set defaults
for a specific ColdFusion application.
The cfapplication tag enables application variables unless they are disabled in the
ColdFusion Administrator. The ColdFusion Administrator setting also overrides the
sessionManagement attribute. For more information, see Advanced ColdFusion
Administration.
Server, Application, and Session Variables
When you display, set, or update variables in the server, application, and session
cflock tag with the scope attribute. For server variables, specify the
clientStorage; you cannot specify Registry.
Example
scopes, use the
"Server" scope. For application variables, specify the "Applicat ion" scope. For
session variables, specify the "Session" scope. For information about locking server,
application, and session scopes, see cflock on page 174.
If ColdFusion is running on a cluster, you must specify either Cookie or a data source
name for
<!------------------------------------------------------------ This example shows how cflock can be used to guarantee the
consistency of data updates to variables in the Application,
Server, and Session scopes.
Copy the following code into an Application.cfm
<P>cfapplication defines scoping for a ColdFusion application and
enables or disables the storing of application and/or session
variables. This tag is placed in a special file called
Application.cfm that is run before any other CF template in a
directory where the Application.cfm file appears.
<cfapplication name = "ETurtle"
sessionTimeout = #CreateTimeSpan(0, 0, 0, 60)#
sessionManagement = "Yes">
<!------------------------------------------------------------Initialize the session and application variables
used by E-Turtleneck. Use the session scope for the session
variables.
<cfset session.size = "">
</cfif>
<cfif NOT IsDefined("session.color")>
<cfset session.color = "">
</cfif>
</cflock>
<!---------------------------------------------------------------Use the application scope for the application variable. This
variable keeps track of the total number of turtlenecks sold.
<cfoutput>
E-Turtleneck is proud to say that we have sold
#application.number# turtlenecks to date.
</cfoutput>
</cflock>
<!--- End of Application.cfm --->
40Chapter 2 ColdFusion Tags
cfassociate
DescriptionAllows subtag data to be saved with the base tag. Applies only to custom tags.
CategoryWeb application framework tags
Syntax
<cfassociate baseTag = "base_tag_name"
dataCollection = "collection_name">
See alsocfapplication, cfauthenticate, cferror, cflock, cfmodule
Attributes
AttributeDescription
baseTagRequired. The name of the base tag.
dataCollectionOptional. The name of the structure in which the base tag
stores subtag data. The default is
AssocAttribs.
UsageCall this tag within a subtag to save subtag data in the base tag.
ColdFusion saves subtag attributes in a structure whose default name is
AssocAttribs. Use the DataCollection attribute to specify a different structure
name. Specify a structure name when the base tag can have multiple sub tags and
you want to segregate subtag attributes.
If the custom tag uses an attribute collection, the attributes passed in the attribute
collection are saved as independent attribute values, with no indication that they
were grouped together in a structure within the custom tag.
Example
<!--- Find the context --->
<cfif thisTag.executionMode is "start">
<!--- Associate attributes
This code occurs in a custom tag’s sub tag. --->
<cfassociate baseTag = "CF_TAGBASE">
<!--- Define defaults for attributes --->
<cfparam name = "attributes.happy" default = "Yes">
<cfparam name = "attributes.sad" default = "No">
...
Alphabetical List of ColdFusion Tags41
cfauthenticate
DescriptionAuthenticates a user, setting a security context for the application. For more
username = "user_ID"
password = "password"
setCookie = "Yes" or "No"
throwOnFailure = "Yes" or "No"
authType = "Basic" or "X509">
See alsocfapplication, cfassociate, cferror, cflockcfmodule
Attributes
AttributeDescription
securityContextRequired. Security context with which the user is authenticated.
This context must be defined in the security system.
usernameRequired. User to authenticate.
passwordRequired. User password.
setCookieOptional. Default is Yes. Indicates whether ColdFusion sets an
encrypted cookie to contain authentication information. The
cookie’s contents include user name, security context, browser
remote address, and the HTTP user agent.
throwOnFailureOptional. Default is Yes. Indicates whether ColdFusion throws an
exception (of type SECURITY) if authentication fails.
authTypeOptional. Indicates the type of authentication ColdFusion uses.
Basic specifies that authentication uses username/password
•
(default).
•
X509 specifies that authentication uses X.509 client certificates
passed to the Web server from a browser using SSL.
UsageCode this tag in the Application.cfm file to set a security context for an application.
Call the
If you specify No for
application (perhaps in an
If you specify
cftry/cfcatch block to handle possible exceptions programmatically.
IsAuthenticated function to determine if the user has been authenticated.
setCookie, you must call cfauthenticate for every page in the
Application.cfm file).
throwOnFailure = "Yes", you can enclose cfauthenticate in a
Example<!--- This example shows the use of cfauthenticate
in an Application.cfm file --->
<cfif NOT IsAuthenticated()>
<cftry>
<cfauthenticate securityContext = "Allaire" username = #user#
password = #pwd#>
42Chapter 2 ColdFusion Tags
<cfcatch type = "Security">
<!--- the message to display --->
<H3>Authentication error</H3>
<cfoutput>
<!--- Display the message. Alternatively, you might place
code here to define the user to the security domain. --->
<P>#cfcatch.message#
</cfoutput>
</cfcatch>
</cftry>
</cfif>
<cfapplication name = "Personnel">
...
Alphabetical List of ColdFusion Tags43
cfbreak
DescriptionUsed to break out of a cfloop.
CategoryFlow-control tags
Syntax
<cfbreak>
See alsocfabort, cfexecute, cfif/cfelseif/cfelse, cflocation, cfloop , cfswitch/
cfcase/cfdefaultcase, cfthrow, cftry cfcatch
Example<!--- This example shows the use of cfbreak to exit
a loop when a condition is met --->
<!--- select a list of courses and use cfloop to find a condition
and then break the loop --->
<cfquery name = "GetCourses" dataSource = "cfsnippets">
SELECT *
FROM courses
ORDER by Course_Num
</cfquery>
<html>
<head>
<title> cfbreak Example </title>
</head>
<body bgcolor = silver>
<H1>cfbreak Example</H1>
<P>This example uses cfloop to cycle through a query to find a
value. (In our example, a list of values corresponding to courses in the
cfsnippets datasource).
When the conditions of the query are met, cfbreak stops the loop.
...
<!--- loop through the query until value is found,
then use cfbreak to exit the query --->
<cfloop query = "GetCourses">
<cfif GetCourses.Course_Num is form.courseNum>
<cfoutput>
<H4>Your Desired Course was found:</H4>
<PRE>#Number##Descript#</PRE></cfoutput>
<cfbreak>
<cfelse>
<BR>Searching...
</cfif>
</cfloop>
</cfif>
</body>
</html>
44Chapter 2 ColdFusion Tags
cfcache
DescriptionSpeeds up page rendering when dynamic content does not have to be retrieved each
time a user accesses the page. To accomplish this,
that contain the static HTML returned from a ColdFusion page.
You can use cfcache for simple URLs and URLs that contain URL parameters.
See alsocfflush, cfheader, cfhtmlhead, cfsetting, cfsilent
Attributes
AttributeDescription
actionOptional. One of the following:
•
cacheSpecifies server-side caching. The default is cache.
flushRefresh the cached page. If you specify flush, you
•
can also specify the
clientCacheSpecifies browser caching.
•
directory and expireURL attributes.
• optimalSpecifi es opti mal cac hing th rough a co mbina tio n
of server-side and browser caching.
For more information, see the Usage section.
usernameOptional. When required for basic authentication, a valid
passwordOptional. When required for basic authentication, a valid
protocolOptional. Specifies the protocol used to create pages from
timeoutOptional. DateTime that specifies the oldest acceptable
username.
password.
cache. Either
http:// or https://. The default is http://.
cached page. If the cached page is older than the specified
datetime, ColdFusion refreshes the page. By default,
ColdFusion uses all ca ched p age s. For exam ple, if y ou w ant a
cached file to be no older than 4 hours, code the following:
directoryOptional. Used with action = "flush". Specifies the fully
qualified path of a directory that contains the
be used when
action = "flush". The default is the directory
cfcache.map to
of the current page.
cacheDirectoryOptional. Specifies the fully qualified path of the directory
where pages are to be cached. The default is the directory of
the current page.
expireURLOptional. Used with
action = "flush". ExpireURL takes a
URL reference, including wildcards, that ColdFusion matches
against all mappings in the cfcache.map file. The default is to
flush all mappings. For example:
"foo.cfm" matches "foo.cfm"
"foo.cfm?*"
matches "foo.cfm?x = 5" and "foo.cfm?x = 9"
portOptional. The port number of the web server from which the
page is requested. The port number defaults to 80. The port
number is useful because the
cfcache code calls cfhttp. If
the port number is specified correctly in the internal call to
cfhttp, the URL of each retrieved document is resolved to
preserve links.
UsageTo enable the simplest form of caching, you just code cfcache at the top of a page.
With the
action attribute, you can specify server -side caching, browser caching, or a
combination of the two . The adva nta ge of browser caching is that it takes no
ColdFusion resources; the browser stores pages in its own cache, improving
performance. The advantage of using a combination of the two forms of caching is
that it optimizes perfo rman ce; if th e browser cache times out, th e se rver can retrieve
cached data from its own cache.
In addition to storing cached files,
control caching. It uses a format similar to a Windows INI file. The mapping of a URL
with parameters is stored as follows. Assume a directory c:\InetPub\wwwroot\dir1
that has a CFM file called
parameters. The cfcache.map file entries for foo.cfm looks like this:
[foo.cfm]
Mapping = C:\InetPub\wwwroot\dir1\CFCBD.tmp
SourceTimeStamp = 08/31/1999 08:59:04 AM
The cfcache.map file in a d irectory stores mappings for that directory only. If the
timestamp of the underlying page changes, ColdFusion updates the cache file for
that URL. ColdFusion uses the SourceTimeStamp field to determine whether the
currently cached file is up to date .
You can refresh the cache in the following ways:
•
timeout attributeColdF u sion tes ts th e tim es tam p of the c a che d file ag ains t th e
timeout attributeIf the cached file ’s timestamp is older than timeout, it deletes
the old file and creates a new one. You can use fixed dates if necessary, but it's
better to use relative dates. This works for seconds, hours, days, weeks, years, etc.
action = "flush"You use action = "flush" to force the clean up of cached
•
files. It can take two attributes,
directory and expireURL.
•ManuallyManually or programmatically (using cffile), delete .tmp files. This
is not recommended.
Note the following regarding cfcache:
•cfcache requir es that C oldFusio n Server "si multaneous r equest s" be gr eater than
1. When a cache file is generate d, the r eques ted page req uir es two con nection s to
satisfy the request. When a cached file is found, onl y one request is required.
•Debug settings have no effect on
turns it on. When generating a cached file,
showDebugOutput = "No"
.
cfcache unless the application page explicitly
cfcache uses cfsetting
•ColdFusion does not cache pages that are dependent on any thing other than
URL parameters.
•To use
protocol = "http://".
cfcache with the Secure Sockets Layer (SSL), specify
•If an application page returns an error, the error page is cached.
Example<!--- This example produces as many cached files as there
<H3>This is a test of some simple output</H3>
<cfparam name = "URL.x" default = "no URL parm passed" >
<cfoutput>The value of URL.x = # URL.x #</cfoutput>
</body>
</html>
Alphabetical List of ColdFusion Tags47
cfcol
DescriptionDefines table column header , width, alignment, and text. Used only inside a cftable.
CategoryData output tags
Syntax
<cfcol header = "column_header_text"
width = "number_indicating_width_of_column"
align = "Left" or "Right" or "Center"
text = "double_quote_delimited_text_indicating_type_of_text">
See alsocfcontent, cfoutput, cftable
Attributes
Attribute Description
headerRequired. The text for the column’s header.
widthOptional. The width of the column in characters (the default is 20). If the
length of the dat a dis playe d exce eds th e wid th v alue, t he dat a is trunca ted
to fit.
alignOptional. Column alignment, Left, Right, or Center.
textOptio nal. Doubl e-quote delimi ted t ext that de termin es what displays in the
column. The rules for the text attribute are identical to the rules for
cfoutput sections; it can consist of a combination of literal text, HTML
tags, and query record set field references. You can embed hyperlinks,
image references, and input controls in columns.
Example
<!--- This example shows the use of cfcol and cftable
to align information returned from a query --->
<!--- this query selects employee information from the
cfsnippets data source --->
<cfquery name = "GetEmployees" dataSource = "cfsnippets">
SELECT Emp_ID, FirstName, LastName, EMail, Phone, Department
FROM Employees
</cfquery>
<html>
<head>
<title>
cfcol Example
</title>
</head>
<body>
<H3>cfcol Example</H3>
<!--- Note the use of the HTMLTable attribute to display the
cftable as an HTML table, rather simply as PRE formatted
information --->
HTMLTable>
<!--- each cfcol tag sets the width of a column in the table,
as well as specifying the header information and the text/CFML
with which to fill the cell --->
DescriptionAllows you to create and administer Verity collections.
CategoryExtensibility tags
Syntax
<cfcollection action = "create" or "repair" or
"delete" or "optimize" or "map"
collection = "collection_name"
path = "path_of_verity_directory"
language = "English" or "German" or "Finnish" or "French" or "Danish"
or "Dutch" or "Italian" or "Norwegian" or "Portuguese" or "Spanish"
or "Swedish">
See alsocfexecute, cfindex, cfgraph, cfobject, cfreport, cfsearch, cfservlet,
cfwddx
Attributes
Attribute Description
actionRequired. Specifies the action to perform:
createCreates a collection using the specified path and optionally
•
specified language.
•
repairFixes data corruption in a collection.
• deleteDestroys a collection.
• optimizePurges and reorganizes data for efficiency.
•
mapAssigns an alias to an existing collection.
collection Required. Specifies a collection name or an alias if
action = "map"
pathRequired for create and map. Speci fie s a p ath to the Verity collection. The
effect of the
•
create creates a directory for Verity. The path is composed of the
directory p ath sp eci f ie d in the
the
path attribute depends on the action that you specify:
path attribute, with the name specified in
collection attribute appended to it. Thus, the full directory path is
"path_name\collection_name\." For example, if the pathname is
"C:\Col\," and the collection name is "myCollection," the full directory
path is "C:\Col\myCollection\."
map provides a name with which ColdFusion can reference an existing
•
collection. The name is specified with the
alias for the collection, which can be used in
collection attribute. It is an
cfindex, and to reinst ate a
collection after you re-install ColdFusion. The directory path specified
with the path attribute is the full pathname of the Verity directory.
Therefore, to reference the directory created in the previous example,
specify "C:\Col\m yCo llection\."
50Chapter 2 ColdFusion Tags
Attribute Description
language Optional for create. To use the language attribute you must have the
ColdFusion International Search Pack installed. Options are:
• English (default)
• German
• Finnish
• French
• Danish
• Dutch
• Italian
• Norwegian
• Portuguese
• Spanish
• Swedish
Usagecfcollection works only at the collection level. To add content to a collection, use
cfindex.
Example
Note the following regarding mapped collections:
•Mapping allows you to assign an alias to a V erity collection created by a tool other
than ColdFusion.
•The
action, collection, and path attributes are required.
•The path must point to a valid Verity collection; mapping does not validate the
path.
•Deleting a mapped collection unregisters the alias; the base collection is not
deleted.
<!--- This example shows the basic functionality
of the cfcollection tag (create, repair, optimize, delete) --->
<html>
<head>
DescriptionDefines the MIME type returned by the current page. Optionally, lets you specify the
name of a file to be returned with the page.
CategoryData output tags
Note
In the ColdFusion Administrator, the security settings on the Tag Restrictions page
under ColdFusion Basic Security may prevent
cfcontent tag must be enabled. For more information, see Advanced ColdFusion
Administration.
cfcontent from executing. The
Syntax
<cfcontent type = "file_type"
deleteFile = "Yes" or "No"
file = "filename"
reset = "Yes" or "No">
See alsocfcol, cfoutput, cftable
Attributes
Attribute Description
typeRequired. Defines the File/ MIME content type returned by the current
page.
deleteFile Optional. Yes or No. Yes deletes the file after the download operation.
Defaults to No . This attribut e appli es onl y if y ou spe cify a file with the
attribute.
fileOptional. The name of the file being retrieved.
resetOptional. Yes or No. Yes discards output that precedes the call to
cfcontent. No preserves the output that precedes the call. Defaults to
Yes. The
a file, the
reset and file attributes are mutually exclusive. If you specify
reset attribute has no effect. See Note.
Note
Consider setting
reset to No if you call cfcontent from a custom tag and do not
want the tag to discar d the curr en t page when it is called fro m another ap plicat ion or
custom tag.
file
Example
<!--- This example shows the use of cfcontent to return the
contents of the CF Documentation page dynamically to the browser.
You may need to change the path and/or drive letter.
(graphics will not display) --->
<html>
<head>
<title>
cfcontent Example
Alphabetical List of ColdFusion Tags53
</title>
</head>
<body>
<H3>cfcontent Example</H3>
<!--- Files may be set to delete after downloading,
allowing for the posting of changing content. --->
<cfcontent type = "text/html"
file = "c:\inetpub\wwwroot\cfdocs\main.htm" deleteFile = "No">
</body>
</html>
<!--- This example shows how the reset attribute changes textual
output. --->
<html>
<head>
<title>
cfcontent Example 2
</title>
</head>
<body>
<H3>cfcontent Example 2</H3>
<P>This example shows how the reset attribute changes the output for
<P>This example shows how the reset attribute changes the output for
text.</P>
<P>reset = "No ": 123<cfcontent type = "text/html" reset = "No ">456</P>
</body>
</html>
54Chapter 2 ColdFusion Tags
cfcookie
DescriptionDefines cookie variables, including expiration and secur ity options.
CategoryVariable manipulation tags
Syntax
<cfcookie name = "cookie_name"
value = "text"
expires = "period"
secure = "Yes" or "No"
path = "url"
domain = ".domain">
See alsocfparam, cfregistry, cfsavecontent, cfschedule, cfset
Attributes
Attribute Description
nameRequired. The name of the cookie variable.
valueOptional. The value assigned to the cookie variable.
expiresOptional. Schedules the expiration of a cookie variable. Can be specified
as a date (as in, 10/09/97), number of days (as in, 10, 100), "Now", or
"Never". Using Now effectively deletes the cookie from the client browser.
secureOptional. Yes or No. Specifies that the variable must transmit securely. If
the browser does not support Secure Socket Layer (SSL) security, the
cookie is not sent.
pathOptional. Specifies the URL within a domain to which this cookie applies.
To specify more than one URL, use multiple
cfcookie tags.
path = "/services/login"
If you specify a path, you must also specify a value for the domain
attribute.
domainOptional. Specifies the domain for which the cookie is valid and to which
the cookie content can be sent. An explicitly specified domain must start
with a dot. If the value is a subdomain, the valid domains are any domain
names ending in this string.
For domain names ending in country codes (such as
subdomain specification must contain at least three periods; for example,
.mongo.stateu.us. For special top level domains, only two periods are
needed, as in
When spec ifying a
Separate multiple entries with a semicolon.
UsageCookies written with
session ends. Until the browser is closed, the cookie resides in memory. If you do not
have an expires attribute in a cfcookie, the cookie exist s unt il the br o wse r is clo sed.
It is never written to the
.jp, .us), the
.macromedia.com.
path value, you must include a valid domain.
cfcookie are written to the cookies.txt file when the browser
cookies.txt file.
Alphabetical List of ColdFusion Tags55
Warning
Do not set a cookie variable on the same page that you use the
cflocation tag. If you
do, the cookie is never saved on the browser; therefore, it is of no value.
Example
<!--- This example shows how to set a cfcookie variable,
and also how to delete that variable --->
<!--- First select a group of users who have entered
comments into the sample database --->
<cfquery name = "GetAolUser" dataSource = "cfsnippets">
SELECT EMail, FromUser, Subject, Posted
FROM Comments
</cfquery>
<html>
<head>
<title>
cfcookie Example
</title>
</head>
<body bgcolor = silver>
<H3>cfcookie Example</H3>
<!--- if the URL variable delcookie exists,
set the cookie’s expiration date to NOW --->
<cfif IsDefined("url.delcookie") is True>
<cfcookie name = "TimeVisited"
value = "#Now()#"
expires = "NOW">
<cfelse>
<!--- Otherwise, loop through the list of visitors,
and stop when you match the string aol.com in the
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>
56Chapter 2 ColdFusion Tags
</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>
</body>
</html>
Alphabetical List of ColdFusion Tags57
cfdirectory
DescriptionHandles interactions with dire ctories.
CategoryFile management tags
Note
In the ColdFusion Administrator, the security settings on the Tag Restrictions page
under ColdFusion Basic Security may prevent
cfdirectory to execute, it needs to be enabled. For more information, see
for
Advanced ColdFusion Administration.
If you write ColdFusion applications that run on a server used by multiple
customers, you must consider the security of the files and directories that could be
uploaded or otherwise man ipulated by
cfdirectory. For more information about
securing ColdFusion tags, see Advanced C oldFusi on Admi nist ration.
cfdirectory from executing. In order
Syntax
<cfdirectory action = "directory action"
See alsocffile
Attributes
AttributeDescription
actionOptional. Define s the action to be tak en wit h directory (ies) sp ecified i n
directoryRequired. The name of the directory to perform the action against.
nameRequired for
filterOptional for
directory = "directory name"
name = "query name"
filter = "list filter"
mode = "permission"
sort = "sort specification"
newDirectory = "new directory name">
directory. Options are:
• list (default)
•
create
• delete
• rename
action = "list". Ignored by all other actions. Name of
output query for directory listing.
action = "list". Ignored by all other actions. File
extension filter applied to returned names. For example:
one mask filter can be applied at a time.
*.cfm. Only
58Chapter 2 ColdFusion Tags
AttributeDescription
modeOptional. Used with action = "Create" to define the permission s for
a directory on UNIX and Linux platforms. Ignored on Windows.
Options correspond to the octal values of the UNIX
chmod command.
From left to right, permissions are assigned for owner, group, and
other.
For example:
•
mode = "644"Assigns read/write pe rmiss ions for th e own er, and
read permissions for the group and other.
•
mode = "666"Assigns read/write permissions for owner, group,
and other.
•
mode = "777"Assigns read, write, and execute permissions for
all.
sortOptional for action = "list". Ignored by all other actions. The
query columns by which to sort the direct ory lis ti ng. Any comb ina t io n
of columns from query output can be specified in comma-separated
list. You can specify ASC (ascending) or DESC (descending) as
qualifiers for column names. ASC is the default. For example:
sort = "dirname ASC, filename2
DESC, size, datelastmodified"
newDirectoryRequired for action = "rename". Ignored by all other actions. The
new name of the directory specified in the
directory attribute.
UsageWhen using the action = "list", cfdirectory returns five result columns you can
reference in your
cfoutput:
•nameDirectory entry name.
•sizeSize of directory entry.
•
typeFile type: File for File or Dir for Directory.
•dateLastModifiedDate an entry was last modified.
•attributesFile attributes, if applicable.
•
mode(UNIX and Linux only) Octal value that specifies the permissions setting
for the directory. For information about octal values, see the UNIX
chmod shell command.
the
man pages for
You can use the following result columns in standard CFML expressions, preceding
the result column name with the query name:
This example shows the use of cfdirectory to display
the contents of the snippets directory in CFDOCS.
Alphabetical List of ColdFusion Tags59
---------------------------------------------------------------------->
<html>
<head>
<title>
cfdirectory Example
</title>
</head>
<body>
<H3>cfdirectory Example</H3>
<!--- use cfdirectory to give the contents of the
snippets directory, order by name and size
(you may need to modify this path) --->
<cfdirectory directory = "c:\inetpub\wwwroot\cfdocs\snippets"
name = "myDirectory"
sort = "name ASC, size DESC">
<!--- Output the contents of the cfdirectory as a cftable --->
<cftable query = "myDirectory">
<cfcol header = "name:"
text = "#Name#">
<cfcol header = "SIZE:"
text = "#Size#">
</cftable>
</body>
</html>
60Chapter 2 ColdFusion Tags
cfdump
DescriptionOutputs variables for debugging purposes. Using cfdump, you can display the
contents of simple variables, queries, arrays, structures, and WDDX variables created
cfwddx.
with
CategoryVariable manipulation tags
Syntax
<cfdump var = #variable_name#>
See alsocfcookie, cfdump, cfparam, cfregistry, cfsavecontent, cfschedule, cfset,
cfwddx
Attributes
AttributeDescription
varRequired. The name of the variable to display, enclosed in pound
signs. The
cfdump tag can output the following variable types:
• simple
• query
• Structure
• Array
• WDDX
Alphabetical List of ColdFusion Tags61
cferror
DescriptionEnables the disp lay of customized HTML pages when errors occur. This lets you
maintain a consistent look and feel within your application, even when errors occur.
typeRequired. The type of error that the custom error page handles.
TemplateRequired. The relative path to the custom error page.
mailToOptional. The e -ma il addre ss of th e admi nistrat or to noti fy of the error.
The value is available to your custom error page in the MailTo
property of the error object. For example:
exceptionRequired. Type of exception. Required if
"monitor".
UsageUse the
You generally embed the
cferror tag to customize error messages for all the pages in an application.
cferror tag in the Application.cfm file. For more
information, see Advanced ColdFusion Administration.
#error.mailTo#.
type = "exception" or
To ensure that error pages display successfully, do not use the cfencode utility to
encode pages that include
cferror.
62Chapter 2 ColdFusion Tags
Templates
The following table describes the template to use for each type of error.
Template type DescriptionUse
ExceptionDynamically invoked by the CFML
language processor when it detects
an unhandled exception condition.
You can specify exception-handling
templates in several wa ys:
• As part of an application using
cferror type = "exception"
• Using the ColdFusion
Administrator
RequestIncludes only the error variables
described in the Usage section.
Cannot include CFML tags.
ValidationHandles data input validation erro rs
that occur when submitting a form.
MonitorDynamically invoked by the CFML
language processor when it first
detects an excep tio n cond iti on,
before it searches for
cfcatch
or cferror handlers for the
cftry/
exception.
Uses the full range of CFML
tags, making it more powerful
than
cferror type =
"request"
.
Use as a backup error handler
for sites with high user
interface requir ements.
You must include the
validation error handler in the
Application.cfm file.
Use for monitoring and
debugging exc eption handl ing
within complex appli ca tio ns.
Error variables
The exception-handling template specified in the template attribute of the cferror
tag contains one or more error variables. ColdFusion substitutes the value of the
error variable when an error displays.
Alphabetical List of ColdFusion Tags63
The following table lists the error variables:
Template type Error variableDescription
Exception
Request
Monitor
error.diagnostics
error.mailTo
Detailed error diagnostics from
ColdFusion Server.
E-mail address of administrator notified
(corresponds to the value set in the
mailTo attribute of cferror).
error.dateTime
error.browser
Date and time when the error occurred.
Browser that was running w hen t he error
URL query string of the client's request.
Text for header of validation message.
Unordered list of validation errors that
occurred.
error.validationFooter
Text for footer of valida tion message.
Example
Note
If you specify
prefix
cferror.dateTime.
<!--- This example shows the use of cferror. --->
<html>
<head>
<title>cferror Example</title>
</head>
<body>
<H3>cferror Example</H3>
<P>cferror provides the ability to display customized
HTML pages when errors occur. This allows you to
maintain a consistent look and feel within your
application even when errors occur. Note that no CFML
can be displayed in the resulting templates except
for the specialized error variables.
<P>cftry/cfcatch provides a more interactive way to
cferror for Error; for example, cferror.diagnostics, cferror.mailTo, or
type = "exception" or type = "monitor", you can substitute the
64Chapter 2 ColdFusion Tags
handle your CF errors within a CF template than cferror,
but cferror is still a good safeguard against general
errors.
<P>You can also use cferror within the Application.cfm
to specify error handling responsibilities for an entire
application.
<!--- Example of cferror call within a template --->
<cferror type = "REQUEST"
<!--- Example of the template to handle this error --->
<!--<html>
<head>
<title>We’re sorry -- An Error Occurred</title>
</head>
<body>
<UL>
<cfoutput>
<LI><B>Your Location:</B> #error.remoteAddress#
<LI><B>Your Browser:</B> #error.browser#
<LI><B>Date and Time the Error Occurred:</B> #error.dateTime#
<LI><B>Page You Came From:</B> #error.HTTPReferer#
<LI><B>Message Content</B>: <BR><HR width = 50%>
DescriptionEnables ColdFusion developers to execute a process on a server computer.
CategoryExtensibility tags
Syntax
<cfexecute name = " ApplicationName "
arguments = "CommandLine Arguments"
outputFile = "Output file name"
timeout = "Timeout interval in seconds">
...
</cfexecute>
See alsocfcollection, cfindex, cfgraph, cfobject, cfreport, cfsearch,
cfservlet, cfwddx
Attributes
AttributeDescription
nameRequired. The full pathname of the application to execute.
Note: On Windows, you must specify the extension as part of the
application’s name. For example, myap p.e xe,
arguments Optional. Command-line arguments passed to the application.
arguments is specified as a string, it is processed as follows:
If
• On Windows, the entire string is passed to the Windows process
control subsystem for pars in g.
• On UNIX, the string is tokenized in to an array of argumen ts. The def ault
token separator is a space; arguments with embedded spaces may be
delimited by double quotes.
If
arguments is passed as an array, it is processed as follows:
• On Windows, the array elements are concatenated into a string of
tokens, separated by spaces. The string is passed to the Windows
process control subsystem for parsing.
• On UNIX, the elements of the
arguments array are copied into a
corresponding array of exec() arguments.
outputFile Optional. The file to which to direct the output of the program. If not
specified, the output is displayed on the page from which it was called.
timeoutOptional. Indica tes how long , in seconds , the ColdFusi on executing thread
waits for the spawned process. A timeout of 0 is equivalent to the
non-blocking m ode of ex ecuting. A very h igh time out value is equ ivalent t o
a blocking mode of execution. The default is 0; therefore, the ColdFusion
thread spawns a process and return s without wa iting for the process to
terminate.
If no output fil e is s pecif ied, an d the t imeou t valu e is 0, the pro gram o utput
is discarded.
66Chapter 2 ColdFusion Tags
Usagecfexecute is available on Windows NT 4.0 and UNIX platforms. Do not put other
ColdFusion tags or functions between the start and the end tags of
cfexecute tags cannot be nested.
cfexecute. The
Exceptioncfexecu te throws the following exceptions:
•If the application name is not found: Application File Not Found exception
•If the output file cannot be opened: Outp ut File Cannot exception
•If the effective user of the ColdFusion executing thread does not have
permissions to execute the process, a security exception is thrown.
•The time out values must be between 0 and th e lo ng es t time ou t v alu e sup port ed
by the operating system.
Example
<!--------------------------------------------------------------------This example illustrates use of the cfexecute tag.
<P>cfexit can be used to abort the processing of the
currently executing CFML custom tag. Execution resumes
following the invocation of the custom tag in the
page that called the tag.
<H3>Usage of cfexit</H3>
<P>cfexit is used primarily to perform a conditional stop
of processing inside a custom tag. cfexit returns control
to the page that called that custom tag, or in the case of
a tag called by another tag, to the calling tag.
<!--- cfexit can be used inside a CFML custom tag, as follows: --->
<!--- Place this code (uncomment the appropriate
sections) inside the CFUSION/customtags directory --->
<!--- MyCustomTag.cfm --->
<!--- This simple custom tag checks for the existence
of myValue1 and myValue2. If they are both defined,
the tag adds them and returns the result to the calling
page in the variable "result". If either or both of the
expected attribute variables is not present, an error message
is generated, and cfexit returns control to the
calling page. --->
<!--- <cfif NOT IsDefined("attributes.myValue2")>
<cfset caller.result = "Value2 is not defined">
<cfexit method = "exitTag">
<!--- <P>The call to the custom tag, and then the result:
<CF_myCustomTag
myvalue2 = 4>
<cfoutput>#result#</cFOUTPUT> --->
<P>If cfexit is used outside of a custom tag, it functions
like a cfabort. For example, the text after this message
will not be processed:
Alphabetical List of ColdFusion Tags69
<cfexit>
<P>This text will not be executed due to the existence of
the cfexit tag above it.
</body>
</html>
70Chapter 2 ColdFusion Tags
cffile
DescriptionHandles all interaction s wi th f i les. The attributes yo u us e w ith cffile depend on the
value of th e
attributes associated with writing a text file.
Note
In the ColdFusion Administrator, the security settings on the Tag Restrictions page
under ColdFusion Basic Security may prevent
execute, it needs to be enabled. For more information, see Advanced ColdFusion Administration.
If you write ColdFusion applications that run on a server used by multiple
customers, consider the security of the files that could be uploaded or otherwise
manipulated by
Administration.
cffile actions
action attribute. For example, if the action = "write", use the
cffile from executing. For cffile to
cffile. For more information, see Advanced ColdFusion
The following sections describe how to use the different actions available with the
cffile tag:
•cffile action = "upload" on page 71
•cffile act ion = "move" on page 75
•cf file action = "rename" on page 76
•cffile act ion = "copy" on page 77
•cffile action = "delete" on page 78
•cffile action = "read" on page 79
•cffile act ion = "readBinary" on page 80
•cffile action = "write" on page 81
•cffile act ion = "append" on page 84
Alphabetical List of ColdFusion Tags71
cffile action = "upload"
DescriptionUploads upload a file specified in a form field to a directory on the Web server.
Note
The mode attribute applies only to ColdFusion on Solaris and HP-UX.
fileFieldRequired. The name of the form field that was used to select the file.
Note: Do not use pound signs (#) to specify the field name.
destinationRequired. The full pathname of the destination directory or full
pathname of the file on the Web server where the file is saved. A
trailing slash must be included in the target directory. Use the
backward slash (\) on Windows; use the forward slash (/) on UNIX.
Note: The directory does not have to be below the root of the Web
server document directory.
nameConflictOptional. Default is Error. Determines how to handle the file if its
name conflicts with the name of a file that already exists in the
directory. Options are:
• ErrorDefault. The file is not saved, ColdFusion stops processing
the page and returns an error.
• SkipNeither saves t he file nor throws an error. This setting allows
custom behavior based on file properties.
• OverwriteReplaces an existing file, if it has the same name as
the cffile destination.
• MakeUniqueGenerate a unique filename for the upload. The
name is stored in the file object variable serverFile. You can
use this variable to record the name used w hen the file w as sav ed.
acceptOptional. Limit the file types accepted. Enter one or more
comma-delimited MIME types that you want to accept. For example,
to allow uploads of GIF and Microsoft Word files, enter:
accept = "image/gif, application/msword"
The browser uses the file extension to determine file type.
72Chapter 2 ColdFusion Tags
AttributeDescription
modeOptional. Defi nes p ermissi ons fo r an up loa ded fi le on UNIX an d Linu x
platforms. Ign ored in Win dows . O pti on v al ues co rres pon d to the octal
values ( not symbolic) of the UNIX
chmod command. Permissions are
assigned for owner, group, and other, respectively.
For example:
•
mode = "644"Assigns read/write pe rmiss ions for th e own er, and
read permissions for the group and other.
mode = "666"Assigns read/write permissions for owner, group,
•
and other.
mode = "777"Assigns read, write, and execute permissions for
•
all.
attributesOptional. A comma-delimited list of file attributes to be set on the file
being uploaded. Options are:
• readOnly
• temporary
• archive
• hidden
• system
• normal
If attributes is not used, the file’s attributes are maintained. If
normal is specified with other attributes, normal is overridden by
whatever other attribute is specified.
Individual attributes must be specified explicitly. For example, if you
specify only the
readOnly attribute, all other existing attributes are
overwritten.
ExampleThe following example creates a uniq ue fi lename i f th ere is a name conflict when the
On Windows, you must include the backward slash (\) after the destination directory
name. On UNIX, you must include the forward slash (/) after the destination
directory. In this example, the specified destination directory is "uploads."
UsageAfter a file upload is completed, you can retrieve status information using file upload
parameters. The status information includes data about the file, such as the file’s
name and the directory where it was saved. File upload status parameters use the
cffile prefix; for example, cffile.clientDirectory. The file status parameters can
be used anywhere other ColdFusion parameters can be used.
Alphabetical List of ColdFusion Tags73
Note
Although the
cffile prefix.
file prefix is still supported, it has been deprecated in favor of the
The following file upload status parameters are available after an upload.
Parameter Description
attemptedServerFileInitial name ColdFusion used when attempting to save a file
clientDirectory Directory location of the file uploaded from the client’s
system
clientFile Name of the file uploaded from the client’s system
clientFileExtExtension of the uploaded file on the client’s system without a
period, for example, txt not .txt
clientFileNameFilename, without an extension, of the uploaded file on the
client’s system
contentSubTypeMIME content subtype of the saved file
contentTypeMIME content type of the saved file
dateLastAccessed Date and time the uploaded file was last accessed
fileExistedIndicates (Yes or No) whether or not the file already existed
with the same path
fileSize Size of the uploaded file
fileWasAppended Indicates (Yes or No) whether ColdFusion appends the
uploaded file to an existing file
fileWasOverwrittenIndicates (Yes or No) whether ColdFusion overwrites a file
fileWasRenamed Indicates (Yes or No) whether the uploaded file is renamed to
avoid a name conflict
fileWasSaved Indicates (Yes or No) whether Cold Fusion saves a file
oldFileSizeSize of a file that was overwritten in the file upload operation
serverDirectoryDirectory of the file save d on the server
serverFile Filename of the file saved on the server
serverFileExt Extension of the uploaded file on the server, without a period
serverFileNameFilename, without an extension, of the uploaded file on the
server
timeCreated Time the uploaded file was created
timeLastModifiedDate and time of the last modification to the uploaded file
74Chapter 2 ColdFusion Tags
Tip
Use the
#cffile.fileExisted#.
cffile prefix to refer to these parameters; for example,
Note
File status parameters are read-only. They are set to the results of the most recent
cffile operation. (If two cffile tags execute, the results of the first are overwritten
by the subsequent cffile operation.)
Example UNIXThe following three exampl es show the use of the mode attribute on UNIX. The first
example creates the file
write, group = read, other = read
<cffile action = "write"
file = "/tmp/foo"
mode = 644>
/tmp/foo with permissions defined as: owner = read/
.
This example appends to the specified file and makes permissions read/write (rw)
for all.
<cffile action = "append"
destination = "/home/tomj/testing.txt"
mode = 666
output = "Is this a test?">
This example uploads a file and sets permissions to owner/group/other = read/
write
/execute.
cffile action = "upload"
fileField = "fieldname"
destination = "/tmp/program.exe"
mode = 777>
Alphabetical List of ColdFusion Tags75
cffile action = "move"
DescriptionMoves a file from one location on the server to another.
sourceRequired. The full pathname of the file to move.
destinationRequired. The full pathname of the directory or full pathname of the file
attributesO ptional. A comma-delimited list of file attributes to be set on the file
to which the file will be moved. If you do not specify the filename, a
trailing slash must be inclu ded in the target when movin g a fil e. Use th e
backward slash (\) on Windows; use the forward slash (/) on UNIX.
being moved. The following file attributes are supported:
• readOnly
• temporary
• archive
• hidden
• system
• normal
attributes is not used, the file’s attributes are maintained. If normal
If
is specified with any other attributes,
normal is overridden by whatever
other attribute is specified.
Individual attributes must be specified explicitly. For example, if you
specify only the
readOnly attribute, all other existing attributes are
overwritten.
ExampleThe following exampl e moves the keymemo.doc file from the c:\files\upload\
On Windows, you must include the backward slash (\) after the destination directory
name if you do not specify a filename. In this example, the specified destination
directory is "memo. "
c:\files\memo\ directory on Windows:
76Chapter 2 ColdFusion Tags
cffile action = "rename"
DescriptionUse cffile with the rename action to rename a file on the server.
sourceRequired. The full pathname of the file to rename.
destinationRequired. The full pathname, including the new name, of the file.
attributesO ptional. A comma-delimited list of file attributes to be set on the file
being renamed. The following file attributes are supported:
• readOnly
• temporary
• archive
• hidden
• system
• normal
If
attributes is not used, the file’s attributes are maintained. If normal
is specified with any other attributes,
normal is overridden by whatever
other attribute is specified.
Individual attributes must be specified explicitly. For example, if you
specify only the
readOnly attribute, all other existing attributes are
overwritten.
ExampleThe following example renames the file
<cffile action = "rename"
source = "c:\files\memo\keymemo.doc"
destination = "c:\files\memo\oldmemo.doc">
keymemo.doc to oldmemo.doc:
Alphabetical List of ColdFusion Tags77
cffile action = "copy"
DescriptionCopies a file from one directory to another on the server.
sourceRequired. The full pathname of the file to copy.
destinationRequired. The full p athname of the direct ory or ful l p a thna me of
attributesOptional. A comma-delimited list of file attributes to be set on the
the file where the cop y of the file i s saved. If you do not s pecify a
filename, you must include the trailing slash. Use the backward
slash (\) on Windows; use the forward slash (/) on UNIX.
file bei ng renamed. The following file att ributes are supported:
• readOnly
• temporary
• archive
• hidden
• system
• normal
If attributes is not used, the file’s attributes are maintained. If
normal is specified with any other attributes, normal is
overridden by whatever other attribute is specified.
Individual attributes must be specified explicitly. For example, if
you specify only the
readOnly attribute, all other existing
attributes are overwritten.
UsageOn Windows, you must include the backward slash (\) after the destination directory
name if you do not specify a filename. In this example, the specified destination
directory is "backup."
ExampleThe following exa mple saves a cop y of the keymemo.doc file in the c:\files\backup\
DescriptionReads a text file. The file is read into a dynamic parameter that you can use anywhere
in the page, like any other dynamic parameter. F or example, you could read a text file
and then insert its contents into a database, or you could read a text file and then use
the find and replace functions to modify its contents.
Note
Using
not intended for use with extremely large files, such as log files, because they can
bring down the server.
CategoryFile management tags
cffile action = "READ" reads the entire text file into memory . Therefore , it is
Syntax
<cffile action = "read"
file = "full_path_name"
variable = "var_name">
See alsocfdirectory
Attributes
Attribute Description
fileRequired. The full pathname of the text file to be read.
variableRequired. The name of the variable that will contain the contents of the
text file after it has been read.
ExampleThe following example creates a variable named "Message " to contain the contents
of the file message.txt.
<cffile action = "read"
file = "c:\web\message.txt"
variable = "Message">
The variable "Message" could then be used in the page. For example, you could
display the contents of the
<cfoutput>#Message#</cfoutput>
message.txt file in the final We b page:
ColdFusion supports a number of powerful functions for manipulating the contents
of text files. You can also use the variable created by a
cffile action = "read"
operation in ArrayToList and ListToArray functions.
For more information about working with strings and arrays, see “String functions”
on page 313 and “Array functions” on page 310.
80Chapter 2 ColdFusion Tags
cffile action = "readBinary"
DescriptionRead a binary file, such as an executable or image file. The file is read into a binary
object parameter you can use anywhere in the page, like any other parameter. To
send it through a Web protocol, such as HTTP or SMTP, or store it in a database, first
convert it to Base64 (see “ToBase64” on page 630).
CategoryFile management tags
Syntax
<cffile action = "readBinary"
file = "full_path_name"
variable = "var_name">
See alsocfdirectory
Attributes
Attribute Description
fileRequired. The full pathname of the file to be read.
variableRequired. The name of the variable that will contain the contents of the
binary file after it has been read.
UsageYou convert the binary file to Base64 to FTP it to another site for upload.
ExampleThe following example creates a variable named "aBinaryObj " to contain the
fileRequired. The full pathname of the file to be created.
outputRequired. The content of the file to be created.
modeOptional. Defines permissions for a file on Solaris or HP-UX. Ignored
on Windows. Valid entries correspond to the octal values (not
symbolic) of the Unix c hmod c ommand. Permis sions are ass igned for
owner, group, and other, respectively.
For example:
mode = "644"Assigns read/write pe rmiss ions for th e own er, and
•
read permissions for the group and other.
•
mode = "666"Assigns read/write permissions for owner, group,
and other.
•
mode = "777"Assigns read, write, and execute permissions for
all.
addNewLineOptional. Yes or No. If Yes, a new line character is appended to the
text that is written to the fil e. If No, no n ew li ne c har act er is app end ed
to the text. The default value is Yes.
82Chapter 2 ColdFusion Tags
AttributeDescription
attributesOptional. A comma-delimited list of file attributes to be set on the file
being written. The following file attributes are supported:
• readOnly
• temporary
• archive
• hidden
• system
• normal
If
attributes is not used, the file’s attributes are maintained. If
normal is specified with any other attributes, normal is overridden by
whatever other attribute is specified.
Individual attributes must be specified explicitly. For example, if you
specify only the
readOnly attribute, all other existing attributes are
overwritten.
ExampleThe following example creates a file with the information a user entered into an