Macromedia CFML Language Reference User Manual

CFML Language
Reference
ColdFusion 4.5
Allaire Corporation
Copyright Notice
© 1999 Allaire Corporation. All rights reserved.
This manual, as well as the software described in it, is furnished under license and 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 Allaire Corporation. Allaire Corporation 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 Allaire Corporation.
ColdFusion and HomeSite are federally registered trademarks of Allaire Corporation. HomeSite, the ColdFusion logo and the Allaire logo are trademarks of Allaire Corporation in the USA and other countries. Microsoft, Windows, Windows NT, Windows 95, Microsoft Access, and FoxPro are registered trademarks of Microsoft Corporation. All other products or name brands are the trademarks of their respective holders. Solaris is a trademark of Sun Microsystems Inc. UNIX is a trademark of The Open Group. PostScript is a trademark of Adobe Systems Inc.
Part number: AA-45LNG-RK
Contents
Preface: Welcome To ColdFusion ................................................................xiii
Intended Audience.........................................................................................................................xiv
Welcome to the ColdFusion 4.5 Web Application Server...........................................................xiv
Products and System Requirements ............................................................................................xiv
New features in ColdFusion 4.5 .....................................................................................................xv
New visual tools......................................................................................................................xvi
Enhancements to CFML ........................................................................................................xvi
Better reliability ......................................................................................................................xvi
Improved performance.........................................................................................................xvii
Enterprise connectivity features ..........................................................................................xvii
Security enhancements....................................................................................................... xviii
Language Reference Features.......................................................................................................xix
Using Examples ......................................................................................................................xix
Using Code Snippets..............................................................................................................xix
Using End Tags................................................................................................................................xx
Developer Resources ......................................................................................................................xx
About ColdFusion Documentation..............................................................................................xxi
Documentation updates........................................................................................................xxi
ColdFusion manuals ..............................................................................................................xxi
ColdFusion Server online documentation..........................................................................xxii
Printing ColdFusion documentation...................................................................................xxii
Documentation conventions.............................................................................................. xxiii
Getting Answers .......................................................................................................................... xxiii
Contacting Allaire................................................................................................................ xxiii
Chapter 1: ColdFusion Tags.............................................................................1
Alphabetical List of ColdFusion Tags ............................................................................................. 2
New Tags in ColdFusion 4.5............................................................................................................ 5
ColdFusion Forms Tags................................................................................................................... 6
Database Manipulation Tags.......................................................................................................... 6
Data Output Tags............................................................................................................................. 6
Exception Handling Tags ................................................................................................................ 6
Extensibility Tags ............................................................................................................................. 7
File Management Tags..................................................................................................................... 7
iv CFML Language Reference
Flow-Control Tags ............................................................................................................................7
Internet Protocol Tags......................................................................................................................7
Java Servlet and Java Object Tags....................................................................................................8
Variable Manipulation Tags.............................................................................................................8
Web Application Framework Tags ..................................................................................................8
Other Tags .........................................................................................................................................8
CFABORT...........................................................................................................................................9
CFAPPLET........................................................................................................................................11
CFAPPLICATION ............................................................................................................................13
CFASSOCIATE.................................................................................................................................16
CFAUTHENTICATE........................................................................................................................17
CFBREAK .........................................................................................................................................19
CFCACHE ........................................................................................................................................20
CFCOL..............................................................................................................................................23
CFCOLLECTION .............................................................................................................................25
CFCONTENT...................................................................................................................................28
CFCOOKIE.......................................................................................................................................30
CFDIRECTORY................................................................................................................................33
CFERROR.........................................................................................................................................36
CFERROR Error Variables.......................................................................................................37
CFEXECUTE ....................................................................................................................................40
CFEXIT.............................................................................................................................................42
CFFILE .............................................................................................................................................45
CFFILE ACTION attributes.....................................................................................................46
CFFILE ACTION="Upload"............................................................................................................47
Evaluating the results of a file upload....................................................................................49
CFFILE ACTION="Move"...............................................................................................................51
CFFILE ACTION="Rename" ..........................................................................................................52
CFFILE ACTION="Copy" ...............................................................................................................53
CFFILE ACTION="Delete" .............................................................................................................54
CFFILE ACTION="Read"................................................................................................................54
CFFILE ACTION="ReadBinary".....................................................................................................55
CFFILE ACTION="Write"...............................................................................................................55
CFFILE ACTION="Append"...........................................................................................................58
CFFORM ..........................................................................................................................................59
Incorporating HTML form tags..............................................................................................60
CFFTP ..............................................................................................................................................63
Establishing a Connection with CFFTP.................................................................................63
File and Directory Operations with CFFTP...........................................................................66
CFFTP.ReturnValue Variable..................................................................................................70
Accessing the Columns in a Query Object ............................................................................70
Connection Caching ...............................................................................................................71
CFGRID............................................................................................................................................73
Select mode and form variables.............................................................................................78
Using SELECTMODE="Edit"..................................................................................................78
Using the HREF attribute........................................................................................................78
CFGRIDCOLUMN...........................................................................................................................81
CFGRIDROW...................................................................................................................................86
CFGRIDUPDATE.............................................................................................................................87
Contents v
CFHEADER......................................................................................................................................90
CFHTMLHEAD................................................................................................................................91
CFHTTP ...........................................................................................................................................92
CFHTTPPARAM ..............................................................................................................................98
CFIF/CFELSEIF/CFELSE..............................................................................................................100
CFIMPERSONATE.........................................................................................................................102
CFINCLUDE..................................................................................................................................104
CFINDEX .......................................................................................................................................105
CFINPUT .......................................................................................................................................109
CFINSERT......................................................................................................................................112
CFLDAP..........................................................................................................................................115
CFLOCATION................................................................................................................................121
CFLOCK .........................................................................................................................................122
CFLOOP .........................................................................................................................................129
Index Loops............................................................................................................................129
Conditional Loops.................................................................................................................130
Looping over a Query............................................................................................................131
Looping over a List................................................................................................................132
Looping over a COM Collection or Structure......................................................................133
CFMAIL..........................................................................................................................................135
CFMAILPARAM.............................................................................................................................138
CFMODULE ..................................................................................................................................140
CFOBJECT .....................................................................................................................................143
CFOBJECT TYPE attributes...................................................................................................143
CFOBJECT Type="COM" .............................................................................................................144
CFOBJECT Type="CORBA"..........................................................................................................146
CFOBJECT Type="JAVA"..............................................................................................................147
CFOUTPUT ...................................................................................................................................149
CFPARAM ......................................................................................................................................151
CFPOP............................................................................................................................................154
CFPROCESSINGDIRECTIVE........................................................................................................159
CFPROCPARAM............................................................................................................................160
CFPROCRESULT...........................................................................................................................163
CFQUERY ......................................................................................................................................165
CFQUERYPARAM .........................................................................................................................170
CFREGISTRY .................................................................................................................................174
CFREGISTRY ACTION attributes.........................................................................................174
CFREGISTRY ACTION="GetAll"..................................................................................................175
CFREGISTRY ACTION="Get".......................................................................................................176
CFREGISTRY ACTION="Set".......................................................................................................177
CFREGISTRY ACTION="Delete" .................................................................................................178
CFREPORT.....................................................................................................................................180
CFRETHROW ................................................................................................................................182
CFSCRIPT ......................................................................................................................................184
CFSEARCH.....................................................................................................................................185
CFSELECT......................................................................................................................................189
CFSERVLET ...................................................................................................................................192
CFSERVLETPARAM ......................................................................................................................194
CFSET.............................................................................................................................................197
vi CFML Language Reference
Arrays......................................................................................................................................197
Dynamic variable names ......................................................................................................197
COM objects ..........................................................................................................................197
CFSETTING ...................................................................................................................................199
CFSILENT ......................................................................................................................................201
CFSLIDER......................................................................................................................................202
CFSTOREDPROC ..........................................................................................................................207
CFSWITCH/CFCASE/CFDEFAULTCASE....................................................................................210
CFTABLE........................................................................................................................................212
CFTEXTINPUT..............................................................................................................................214
CFTHROW.....................................................................................................................................218
CFTRANSACTION.........................................................................................................................220
CFTREE..........................................................................................................................................223
CFTREEITEM ................................................................................................................................228
CFTRY/CFCATCH.........................................................................................................................232
CFUPDATE....................................................................................................................................236
CFWDDX .......................................................................................................................................239
Chapter 2: ColdFusion Functions................................................................241
Alphabetical List of ColdFusion Functions.................................................................................242
New Functions in ColdFusion 4.5 ...............................................................................................245
Array Functions.............................................................................................................................245
Authentication Functions............................................................................................................245
Date and Time Functions.............................................................................................................246
Decision Functions.......................................................................................................................246
Display and Formatting Functions..............................................................................................247
Dynamic Evaluation Functions...................................................................................................247
International Functions ...............................................................................................................247
List Functions................................................................................................................................248
Mathematical Functions..............................................................................................................248
Query Functions ...........................................................................................................................249
String Functions............................................................................................................................249
Structure Functions......................................................................................................................250
System Functions..........................................................................................................................250
Other Functions............................................................................................................................250
Abs..................................................................................................................................................251
ACos ...............................................................................................................................................252
ArrayAppend .................................................................................................................................254
ArrayAvg.........................................................................................................................................255
ArrayClear......................................................................................................................................257
ArrayDeleteAt................................................................................................................................258
ArrayInsertAt.................................................................................................................................259
ArrayIsEmpty.................................................................................................................................260
ArrayLen ........................................................................................................................................261
ArrayMax .......................................................................................................................................262
ArrayMin........................................................................................................................................264
ArrayNew.......................................................................................................................................266
ArrayPrepend ................................................................................................................................267
Contents vii
ArrayResize....................................................................................................................................268
ArraySet..........................................................................................................................................269
ArraySort........................................................................................................................................270
ArraySum.......................................................................................................................................271
ArraySwap......................................................................................................................................273
ArrayToList ....................................................................................................................................274
Asc ..................................................................................................................................................275
ASin ................................................................................................................................................276
Atn..................................................................................................................................................278
AuthenticatedContext ..................................................................................................................279
AuthenticatedUser........................................................................................................................280
BitAnd ............................................................................................................................................281
BitMaskClear.................................................................................................................................282
BitMaskRead .................................................................................................................................283
BitMaskSet.....................................................................................................................................284
BitNot.............................................................................................................................................285
BitOr...............................................................................................................................................286
BitSHLN.........................................................................................................................................287
BitSHRN.........................................................................................................................................288
BitXor .............................................................................................................................................289
Ceiling............................................................................................................................................290
Chr..................................................................................................................................................291
CJustify...........................................................................................................................................292
Compare ........................................................................................................................................293
CompareNoCase...........................................................................................................................295
Cos..................................................................................................................................................296
CreateDate.....................................................................................................................................297
CreateDateTime............................................................................................................................299
CreateObject..................................................................................................................................301
Object Types ..........................................................................................................................301
COM...............................................................................................................................................301
CORBA ...........................................................................................................................................302
JAVA................................................................................................................................................303
CreateODBCDate..........................................................................................................................305
CreateODBCDateTime.................................................................................................................307
CreateODBCTime.........................................................................................................................309
CreateTime....................................................................................................................................311
CreateTimeSpan ...........................................................................................................................313
CreateUUID...................................................................................................................................314
DateAdd.........................................................................................................................................315
DateCompare................................................................................................................................317
DateConvert ..................................................................................................................................320
DateDiff .........................................................................................................................................323
DateFormat ...................................................................................................................................325
DatePart.........................................................................................................................................327
Day .................................................................................................................................................329
DayOfWeek....................................................................................................................................330
DayOfWeekAsString .....................................................................................................................331
DayOfYear......................................................................................................................................332
viii CFML Language Reference
DaysInMonth ................................................................................................................................333
DaysInYear ....................................................................................................................................334
DE...................................................................................................................................................335
DecimalFormat .............................................................................................................................336
DecrementValue ...........................................................................................................................337
Decrypt ..........................................................................................................................................338
DeleteClientVariable ....................................................................................................................339
DirectoryExists..............................................................................................................................340
DollarFormat.................................................................................................................................341
Encrypt...........................................................................................................................................342
Evaluate .........................................................................................................................................343
Exp..................................................................................................................................................344
ExpandPath ...................................................................................................................................345
FileExists........................................................................................................................................346
Find ................................................................................................................................................347
FindNoCase...................................................................................................................................348
FindOneOf.....................................................................................................................................349
FirstDayOfMonth..........................................................................................................................350
Fix...................................................................................................................................................351
FormatBaseN.................................................................................................................................352
GetBaseTagData............................................................................................................................353
GetBaseTagList..............................................................................................................................354
GetBaseTemplatePath..................................................................................................................355
GetClientVariablesList..................................................................................................................356
GetCurrentTemplatePath.............................................................................................................357
GetDirectoryFromPath.................................................................................................................358
GetFileFromPath...........................................................................................................................359
GetFunctionList ............................................................................................................................360
GetLocale.......................................................................................................................................361
GetMetricData...............................................................................................................................363
GetProfileString.............................................................................................................................365
GetTempDirectory........................................................................................................................367
GetTempFile..................................................................................................................................368
GetTemplatePath..........................................................................................................................369
GetTickCount................................................................................................................................370
GetTimeZoneInfo .........................................................................................................................371
GetToken .......................................................................................................................................372
Hour ...............................................................................................................................................373
HTMLCodeFormat .......................................................................................................................374
HTMLEditFormat .........................................................................................................................376
IIf ....................................................................................................................................................378
IncrementValue ............................................................................................................................381
InputBaseN....................................................................................................................................382
Insert..............................................................................................................................................383
Int ...................................................................................................................................................384
IsArray............................................................................................................................................385
IsAuthenticated.............................................................................................................................386
IsAuthorized..................................................................................................................................387
IsBinary..........................................................................................................................................390
Contents ix
IsBoolean.......................................................................................................................................391
IsDate.............................................................................................................................................392
IsDebugMode................................................................................................................................393
IsDefined .......................................................................................................................................394
IsLeapYear .....................................................................................................................................395
IsNumeric......................................................................................................................................396
IsNumericDate..............................................................................................................................397
IsProtected.....................................................................................................................................398
IsQuery...........................................................................................................................................401
IsSimpleValue................................................................................................................................402
IsStruct...........................................................................................................................................403
JSStringFormat..............................................................................................................................404
LCase..............................................................................................................................................405
Left .................................................................................................................................................406
Len..................................................................................................................................................407
ListAppend ....................................................................................................................................408
ListChangeDelims.........................................................................................................................409
ListContains ..................................................................................................................................410
ListContainsNoCase.....................................................................................................................412
ListDeleteAt...................................................................................................................................413
ListFind..........................................................................................................................................414
ListFindNoCase.............................................................................................................................416
ListFirst ..........................................................................................................................................417
ListGetAt ........................................................................................................................................418
ListInsertAt ....................................................................................................................................419
ListLast...........................................................................................................................................420
ListLen ...........................................................................................................................................421
ListPrepend ...................................................................................................................................422
ListQualify .....................................................................................................................................423
ListRest...........................................................................................................................................425
ListSetAt.........................................................................................................................................426
ListSort...........................................................................................................................................428
ListToArray ....................................................................................................................................430
ListValueCount..............................................................................................................................431
ListValueCountNoCase ................................................................................................................433
LJustify ...........................................................................................................................................435
Log..................................................................................................................................................436
Log10..............................................................................................................................................437
LSCurrencyFormat .......................................................................................................................438
LSDateFormat...............................................................................................................................441
LSEuroCurrencyFormat ...............................................................................................................443
LSIsCurrency.................................................................................................................................447
LSIsDate.........................................................................................................................................448
LSIsNumeric..................................................................................................................................449
LSNumberFormat.........................................................................................................................450
LSParseCurrency...........................................................................................................................453
Currency output ....................................................................................................................453
LSParseDateTime..........................................................................................................................456
LSParseEuroCurrency ..................................................................................................................458
x CFML Language Reference
LSParseNumber ............................................................................................................................460
LSTimeFormat ..............................................................................................................................461
LTrim..............................................................................................................................................463
Max.................................................................................................................................................464
Mid .................................................................................................................................................465
Min.................................................................................................................................................466
Minute............................................................................................................................................467
Month ............................................................................................................................................468
MonthAsString..............................................................................................................................469
Now................................................................................................................................................470
NumberFormat.............................................................................................................................471
ParagraphFormat..........................................................................................................................474
ParameterExists ............................................................................................................................475
ParseDateTime..............................................................................................................................476
Pi.....................................................................................................................................................478
PreserveSingleQuotes...................................................................................................................479
Quarter...........................................................................................................................................480
QueryAddColumn.........................................................................................................................481
QueryAddRow ...............................................................................................................................483
QueryNew......................................................................................................................................484
QuerySetCell..................................................................................................................................485
QuotedValueList ...........................................................................................................................487
Rand...............................................................................................................................................488
Randomize.....................................................................................................................................489
RandRange ....................................................................................................................................490
REFind ...........................................................................................................................................491
REFindNoCase ..............................................................................................................................494
RemoveChars ................................................................................................................................497
RepeatString..................................................................................................................................498
Replace...........................................................................................................................................499
ReplaceList ....................................................................................................................................500
ReplaceNoCase .............................................................................................................................502
REReplace......................................................................................................................................503
REReplaceNoCase.........................................................................................................................504
Reverse...........................................................................................................................................505
Right...............................................................................................................................................506
RJustify...........................................................................................................................................507
Round.............................................................................................................................................508
RTrim .............................................................................................................................................509
Second ...........................................................................................................................................510
SetLocale........................................................................................................................................511
Locale support.......................................................................................................................511
SetProfileString .............................................................................................................................513
SetVariable.....................................................................................................................................515
Sgn..................................................................................................................................................516
Sin...................................................................................................................................................517
SpanExcluding ..............................................................................................................................518
SpanIncluding...............................................................................................................................519
Sqr ..................................................................................................................................................520
Contents xi
StripCR...........................................................................................................................................521
StructClear.....................................................................................................................................522
StructCopy.....................................................................................................................................523
StructCount ...................................................................................................................................524
StructDelete...................................................................................................................................525
StructFind......................................................................................................................................527
StructInsert....................................................................................................................................528
StructIsEmpty................................................................................................................................530
StructKeyArray ..............................................................................................................................531
StructKeyExists..............................................................................................................................534
StructKeyList .................................................................................................................................535
StructNew......................................................................................................................................538
StructUpdate.................................................................................................................................539
Tan .................................................................................................................................................540
TimeFormat...................................................................................................................................541
ToBase64........................................................................................................................................543
ToBinary ........................................................................................................................................545
ToString .........................................................................................................................................547
Trim................................................................................................................................................549
UCase.............................................................................................................................................550
URLDecode ...................................................................................................................................551
URLEncodedFormat.....................................................................................................................552
Val...................................................................................................................................................553
ValueList ........................................................................................................................................554
Week...............................................................................................................................................555
WriteOutput ..................................................................................................................................556
XMLFormat ...................................................................................................................................557
Year ................................................................................................................................................558
YesNoFormat.................................................................................................................................559
Chapter 3: WDDX JavaScript Objects .........................................................561
WddxSerializer Object..................................................................................................................562
serialize ..................................................................................................................................562
serializeVariable ....................................................................................................................562
serializeValue.........................................................................................................................563
write........................................................................................................................................564
WddxRecordset Object.................................................................................................................565
addColumn............................................................................................................................565
addRows.................................................................................................................................566
getField...................................................................................................................................566
getRowCount.........................................................................................................................567
setField...................................................................................................................................568
wddxSerialize.........................................................................................................................568
Chapter 4: ColdFusion Expressions: Operators and Other Constructs....571
Elements of ColdFusion Expressions..........................................................................................572
Notes on date-and-time values............................................................................................574
xii CFML Language Reference
Notes on using variables.......................................................................................................575
Operators.......................................................................................................................................576
Arithmetic operators.............................................................................................................576
String operators.....................................................................................................................577
Decision, or comparison, operators....................................................................................577
Boolean operators.................................................................................................................579
Operator Precedence....................................................................................................................579
Function Syntax ............................................................................................................................580
Optional arguments in functions.........................................................................................580
Pound Signs...................................................................................................................................581
Pound signs inside CFOUTPUT tags ...................................................................................581
Pound signs inside strings....................................................................................................582
Pound signs inside tag attribute values...............................................................................583
Nested pound signs...............................................................................................................583
Pound signs in general expressions.....................................................................................584
Preface Welcome To ColdFusion
ColdFusion is a rapid application development system for professional developers who want to create dynamic Web applications and interactive Web sites. It provides the fastest way to integrate browser, server, and database technologies into powerful Web applications. With ColdFusion, you can build everything from online stores to sophisticated business systems.
Developing applications with ColdFusion does not require coding in a traditional programming language; instead, you build applications by combining standard HTML with a straightforward server-side markup language, the ColdFusion Markup Language (CFML). This manual documents CFML.
Contents
Intended Audience.......................................................................................... xiv
Welcome to the ColdFusion 4.5 Web Application Server............................. xiv
Products and System Requirements.............................................................. xiv
New features in ColdFusion 4.5 ...................................................................... xv
Language Reference Features......................................................................... xix
Using End Tags ..................................................................................................xx
Developer Resources.........................................................................................xx
About ColdFusion Documentation ............................................................... xxi
Getting Answers ............................................................................................xxiii
xiv CFML Language Reference
Intended Audience
This reference is intended for web developers who have a working knowledge of ColdFusion; that is, you know how to use tags and functions, but you need a comprehensive reference that provides an in-depth description of each tag and function, and examples of how tags and functions are used in the context of an HTML/ CFML page.
Welcome to the ColdFusion 4.5 Web Application Server
The ColdFusion 4.5 release focuses on fundamentals — the fundamentals of delivering your e-business: faster development, better reliability, enhanced scalability, expanded integration, and stronger security.
At the center of the ColdFusion 4.5 release is an application server platform that's been highly optimized with new functionality and native support for UNIX. As a result, your e-business systems will run better and do more. With this release we're launching a new edition of ColdFusion Server for Linux so you can take advantage of the reliability and performance of the hottest new Internet server operating system.
While optimizing the core server, we also enhanced fundamental features including email integration, server-side FTP and HTTP, advanced security, scheduling, and database connectivity — again giving you more reliability and new functionality.
The focus on fundamentals extends to new features. As part of a broad new commitment to Java, ColdFusion 4.5 has a range of new Java integration options from Java CFXs to Java Servlet support to Java object and EJB connectivity. In ColdFusion Studio 4.5, we added new tools to make you more productive including a flexible new project architecture that makes managing and deploying complex Web applications a snap. On the server, we focused on reliability, performance and security with features such as service-level fail-over, Cisco Local Director integration, and OS security integration.
Whether you're revolutionizing your company's HR operations, building the next generation of your firm's global intranet, or launching the next killer .COM company, you'll find the speed, scalability, connectivity, and security you need in ColdFusion 4.5.
Products and System Requirements
ColdFusion has been fully tested on the following platforms and with the following configurations.
ColdFusion Server 4.5 Enterprise Edition for Windows
Windows NT 4.0 SP4+
Intel Pentium or above
150 MB hard disk space
Preface xv
128 MB RAM (256 MB recommended for clustering)
ColdFusion Server 4.5 Enterprise Edition for Solaris
SPARC Solaris 2.5.1, 2.6, or 7 (patch 103582-1B or higher)
128 MB RAM (256 MB recommended for clustering)
200 MB hard disk space
ColdFusion Server 4.5 Enterprise Edition for Linux
Red Hat Linux 6.0 or 6.1
Intel Pentium or above
128 MB RAM (256 MB recommended for clustering)
150 MB hard disk space
ColdFusion Server 4.5 Professional Edition for Windows
Windows 95/98 or Windows NT 4.0
Intel Pentium or above
50 MB hard disk space
32 MB RAM (128 MB recommended)
ColdFusion Server 4.5 Professional Edition for Linux
Red Hat Linux 6.0 or 6.1
Intel Pentium or above
64 MB RAM (128 MB recommended)
100 MB hard disk space
ColdFusion Studio 4.5
Windows 95/98/NT4
Intel Pentium or above
35 MB hard disk space
32 MB RAM (64 MB recommended)
New features in ColdFusion 4.5
A wide range of new features are available in ColdFusion 4.5.
xvi CFML Language Reference
New visual tools
Universal File Browser — Access all your files from a single explorer that integrates access to the Windows file system, ColdFusion RDS servers, and FTP servers. Drag­and-drop between any of these services all in an integrated file browser.
Advanced Project Management — Manage your complex Web application development projects with a new project architecture that gives you more flexibility and control using physical, virtual, and auto-inclusive project folders as well as project resource browsing.
Scriptable Deployment — Deploy applications to complex server configurations with FTP or ColdFusion Remote Development Services (RDS). Use VBScript or Java Script to fully script deployment of projects with granular control over how files uploaded. Setup deployment scripts using a powerful wizard and save scripts for re-use.
Collapsible Code — Work with large, complex scripts and pages more easily by collapsing sections of the code in the editor so you can build sophisticated applications more quickly.
Function Insight — Find the parameters and format for functions instantly and inline as you code.
Image Map Editor — Create image maps right in ColdFusion Studio with a new easy­to-use visual tool.
Configuration Wizard — Setup your work environment so it meets all your needs using any of more than dozen common configurations.
TopStyle CSS Editor — Create and edit standards-compliant cascading style sheets to easily control the look and feel of your web applications.
WML Support — Build wireless Web applications quickly and easily with the complete set of Wireless Markup Language (WML) visual tools.
Enhancements to CFML
Object Scripting — Instantiate and script objects using CFML script in addition to the CFOBJECT tag easier integration with distributed object middleware such as COM and CORBA.
Structured Exception Handling — Exception handling now offers hierarchical exception handling that supports both greater customization and greater access to internal exceptions.
String Conversion Functions — Convert strings quickly and easily to be compatible with Java Script and XML standards.
Better reliability
Server Probes — Guarantee high availability by automatically detecting when a ColdFusion Server or Web server hangs or stops, failing-over to a new machine in a ColdFusion cluster, and restarting the server with problems. (Enterprise Edition only)
Preface xvii
Improved Automatic Server Recovery — Monitor and automatically restart server process in case of failures or critical errors on individual servers not deployed in a cluster.
Clustering Support for Apache — Setup ColdFusion clusters on Linux and Solaris using the Apache Web Server. (Enterprise Edition only)
Automatic Shared Variable Locking — Lock user and session variable reads automatically at the server level to prevent destabilizing conflicts and control thread write contentions. Configure variable locking to meet the specific needs of your applications.
Individual Data Source Control — Enable and disable individual data sources individually without affecting server availability for runtime data source maintenance without server restarts.
Improved performance
Cisco Local Director Integration — Deliver very large scale sites with Cisco Local Director intelligently balancing load based on the load metrics provided by the ColdFusion Servers in a cluster. (Enterprise Edition only)
Client-Side Page Caching — Leverage browser page caching to avoid unnecessary downloads of unchanged pages and improve overall site performance. Programmatically control refresh of client-side cache to ensure users see most up-to­date output.
White Space Removal — Reduce white space left by processed code in application pages to make the pages smaller and faster. Control white space removal programmatically or administratively.
Scriptable Performance Metrics — Track key server metrics at run time through your own scripts for intelligent diagnosis of performance bottlenecks of stability problems in your applications.
Performance Debugging Data — Access detailed debugging information on the performance of each individual page included in an application page that is being debugged.
Enterprise connectivity features
Transaction Commit and Rollback — Control database transactions with programmable commit and rollback support for more reliable and better-managed database interactions.
Java Object and EJB Connectivity — Connect to any Java object or Enterprise JavaBean (EJB) hosted by any major EJB server to extend ColdFusion and access complex business logic or third party distributed components.
Java Servlets — Call Java Servlets hosted by a Servlet Engine such as Allaire JRun from within a ColdFusion application to access extended functionality
xviii CFML Language Reference
Java-based ColdFusion Extensions (CFX) — Extend ColdFusion with new functionality through CFXs created with Java.
Binary Object Support — Use Character Large Binary Object (CLOB) support to encoded binary objects, transmit them via XML, and store them in databases or files.
SQL Bind Parameters — Improve query performance, security and flexibility with explicitly typed query parameters.
WDDX 1.0 — Exchange complex data, including encoded images, between servers and with other programming environments even faster using the latest version of Web Distributed Data Exchange ( WDDX).
OS Command Execution — Execute OS shell scripts, services, executables and batch files from within ColdFusion applications.
LDAP 3.0 — Use all the power of LDAP 3.0 for directory access including file filtering, SSL encryption, and Microsoft Active Directory integration.
Enhanced Mail Integration — Develop more sophisticated and robust email applications with new support for controlling mail headers, BCC, and multiple file attachments.
Improved Server-Side HTTP — Use URL redirection, SSL, cookies, return headers, and more robust server-side HTTP support for building distributed Web applications.
Security enhancements
General OS Security Integration — Secure entire Web applications and control access to files and objects through your existing Windows NT security architecture. Authenticated users in your applications can be limited to privileges authorized through Windows security. (Windows NT Only)
OS Server Sandbox Security — Secure shared hosting environments more easily by creating Server Sandboxes with Windows NT security. OS Server Sandboxes process all requests under the privileges of a designated Windows NT user account (Enterprise Edition for Windows only).
Enhanced Advanced Security — Secure CFML functions and enable CFML code segments to be executed using the run-time security permissions of a designated user.
New Advanced Security Interface — Manage Advanced Security configuration more quickly and easily with a completely redesigned browser-based resource view.
Scriptable Advanced Security Administration — Configure ColdFusion Advanced Security through your own CFML scripts for easier maintenance of ColdFusion Servers.
Preface xix
Language Reference Features
The CFML Language Reference provides descriptions, syntax, usage, and code examples for:
CFML Tags
CFML Functions
JavaScript objects used when implementing web distributed data exchange
(WDDX)
The CFML Language Reference also provides a chapter on expressions, operators, and other CFML constructs.
Using Examples
Each tag and function features a runnable example, using code drawn from the snippets directory (found in webroot\cfdocs\snippets). The display and usage for these examples differs depending on the delivery mechanism:
Printed and PDF documentation — Whenever possible, the printed
documentation displays a complete example. In some cases, extraneous code has been removed to maintain clarity and to conserve space.
HTML documentation — Each tag or function displays an examples button
that you click to execute that element. The online example displays two frames: one that runs the example, and one that displays the associated code. In some cases, code examples are view-only due to logistic, administrative, or security reasons.
The examples button uses a relative reference to access the page that runs the code snippet. Snippets will not run if files have been moved or if ColdFusion Server is not running.
When running examples using ColdFusion Studio on a workstation that isn’t running ColdFusion Server, you will need to specify the ColdFusion Server location using the Browse tab on the Settings dialog box.
Using Code Snippets
The snippets directory contains example code for every CFML tag and function. You can browse this directory to find examples of CFML tag and function usage in many different contexts.
xx CFML Language Reference
Using End Tags
Except where noted in the syntax, CFML tags do not require an end tag. However, all CFML tags (except CFELSE and CFELSEIF) can accept an optional end tag, as follows:
Shorthand — You can use shorthand notation to include the end tag with the
base tag. For example:
<CFABORT/>
Explicit specification — You can specify an end tag explicitly. However, there
can be no white space between the start and end tags. For example:
<CFABORT></CFABORT> <!--- The following will produce a validation error <CFABORT> </CFABORT> --->
You do not typically code optional end tags.
Developer Resources
Allaire Corporation is committed to setting the standard for customer support in developer education, technical support, and professional services. Our Web site is designed to give you quick access to the entire range of online resources.
Allaire Developer Services
Resource Description
Allaire Web site www.allaire.com
Technical Support www.allaire.com/support
Training and Consulting www.allaire.com/services
Developer Community www.allaire.com/developer
Allaire Partners www.allaire.com/partners
General information about Allaire products and services.
Allaire offers a wide range of professional support programs. This page explains all of the available options.
Information about training classes, online courses, and consulting services offered by Allaire.
All of the resources you need to stay on the cutting edge of ColdFusion development, including online discussion groups, Knowledge Base, Component Exchange, Resource Library, technical papers and more.
The Allaire Alliance is a network of solution providers, application developers, resellers, and hosting services creating solutions with ColdFusion.
Preface xxi
About ColdFusion Documentation
ColdFusion documentation is designed to provide support for all components of the ColdFusion development system. Both the print and online versions are organized to allow you to quickly locate the information you need.
In addition to the book set, the documentation is provided in two other formats:
HTML — Browser-based Help references.
Adobe Acrobat (PDF) — Available from the root level on the product CD-ROM
and from the Developer area of Allaire’s Web site at http://www.allaire.com/
developer
Documentation updates
Late additions and corrections to ColdFusion printed documentation are listed in the Documentation Updates page. To reach this page, open the Welcome to ColdFusion page installed with ColdFusion, where you’ll find links to the update page as well as links to other pages containing useful information about ColdFusion, Allaire support options, and Allaire products and services.
For ColdFusion Studio users, you can access the documentation update page by clicking on the Help resource tab and browsing your way through the online help tree to the Allaire Support folder.
.
ColdFusion manuals
The core ColdFusion documentation set consists of the following titles.
Administering ColdFusion Server
Includes instructions for installing ColdFusion Server. Describes configuration options for maximizing performance, managing data sources, setting security levels, and a range of development and site management tasks. If you are administering a ColdFusion site, you’ll need this book to help plan and implement ColdFusion security, load balancing, and for details about tuning the ColdFusion application server.
Developing Web Applications with ColdFusion
Presents the fundamentals of ColdFusion application development and deployment. Also includes detailed information about ColdFusion data sources, user interfaces, and Web technologies.
CFML Language Reference
Provides the complete syntax, with example code, of all CFML tags and functions.
xxii CFML Language Reference
Using ColdFusion Studio
Documents everything you need to know about using ColdFusion Studio, including features like projects, source control integration, as well as the Studio workspace and interface.
ColdFusion Quick Reference Guide
A valuable quick reference to CFML tags, functions, and variables.
ColdFusion Server online documentation
To view the HTML documentation, open the following URL: http://127.0.0.1/
cfdocs/dochome.htm
Note that because the Verity search libraries are not available on Linux for this release, the online documentation search facility is not functional on Linux. If you try to open the search page, a message box opens to explain why the facility is not available.
Acrobat versions of all ColdFusion documentation are available from the root level on
the product CD. If you don’t have a product CD, you can download ColdFusion documentation from the Allaire web site by visiting
developer
and clicking the Documentation link.
.
http://www.allaire.com/
ColdFusion Studio online documentation
Click the Help resource tab in ColdFusion Studio to view online Help pages. The help tree contains ColdFusion documentation and a number of additional developer resources. Studio online documentation is searchable and individual pages can be bookmarked.
Printing ColdFusion documentation
If you are working with an evaluation version of ColdFusion and would like printed documentation, access the Adobe Acrobat files found from the root level on the product CD. If you do not have access to a product CD, you can download the Acrobat files from the Allaire web site: Documentation link.
The Acrobat files offer excellent print output. You can print an entire manual, individual sections, or page ranges of your choice. To get the Acrobat reader, visit:
http://www.acrobat.com.
http://www.allaire.com/developer, click the
Preface xxiii
Documentation conventions
When reading, please be aware of these formatting cues:
Code samples, filenames, and URLs are set in a
Notes and tips are identified by bold type
Bulleted lists present options and features
Numbered steps indicate procedures
Tool button icons are generally shown with procedure steps
Menu levels are separated by the greater than (>) sign
Text for you to type in is set in italics
monospaced font
Getting Answers
One of the best ways to solve particular programming problems is to tap into the vast expertise of the ColdFusion developer community on the Allaire Forums. Other ColdFusion developers on the forum can help you figure out how to do just about anything with ColdFusion. The search facility can also help you search messages going back 12 months, allowing you to learn how others have solved a problem you may be
facing. The Forums is a great resource for learning ColdFusion, but it’s also a great place to see the ColdFusion developer community in action.
Contacting Allaire
Corporate headquarters
Allaire Corporation One Alewife Center Cambridge, MA 02140
Tel: 617.761.2000 Fax: 617.761.2001
http://www.allaire.com
xxiv C FML Language Reference
Technical support
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.761.2100 (outside U.S. and Canada) For complete details about Allaire Product Support options, please refer to the Allaire
Support pages on the Allaire web site: Postings to the ColdFusion Support Forum (
made any time.
http://www.allaire.com/support.
http://forums.allaire.com) can be
Sales
Toll Free: 888.939.2545 Tel: 617.761.2100
Fax: 617.761.2101 Email: sales@allaire.com Web :
http://www.allaire.com/store
C HAPTER 1
Chapter 1 ColdFusion Tags
This chapter describes each of the tags in the ColdFusion Markup Language (CFML). The introduction contains an alphabetical summary of ColdFusion tags, a list of new tags in ColdFusion 4.5, and a list of tags by category. The remainder of this chapter provides complete descriptions of each tag, listed alphabetically.
Contents
Alphabetical List of ColdFusion Tags................................................................ 2
New Tags in ColdFusion 4.5...............................................................................5
ColdFusion Forms Tags ..................................................................................... 6
Database Manipulation Tags.............................................................................6
Data Output Tags................................................................................................6
Exception Handling Tags................................................................................... 6
Extensibility Tags................................................................................................ 7
File Management Tags....................................................................................... 7
Flow-Control Tags .............................................................................................. 7
Internet Protocol Tags........................................................................................ 7
Java Servlet and Java Object Tags...................................................................... 8
Variable Manipulation Tags............................................................................... 8
Web Application Framework Tags .................................................................... 8
Other Tags ........................................................................................................... 8
2 CFML Language Reference
Alphabetical List of ColdFusion Tags
The ColdFusion Markup Language (CFML) consists of a set of tags you use in your 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 each CFML tag.
CFML Tag Summary
CFML Tag Description
CFABORT Stops processing of a ColdFusion page at the tag
location.
CFAPPLET Embeds Java applets in a CFFORM.
CFAPPLICATION Defines application name, activates client variables.
CFASSOCIATE Enables sub-tag data to be saved with the base tag.
CFAUTHENTICATE Authenticates a user and sets the security context for an
application.
CFBREAK Breaks out of a CFML looping construct.
CFCACHE Caches ColdFusion pages.
CFCOL Defines table column header, width, alignment, and text.
CFCOLLECTION Creates and administers Verity collections.
CFCONTENT Defines the content type and, optionally, the filename of
a file to be downloaded by the current page.
CFCOOKIE Defines and sets cookie variables.
CFDIRECTORY Performs typical directory-handling tasks from within
your ColdFusion application.
CFERROR Displays customized HTML error pages when errors
occur.
CFEXECUTE Executes any developer-specified process on the server
machine.
CFEXIT Aborts processing of currently executing CFML custom
tag.
CFFILE Performs typical file-handling tasks from within your
ColdFusion application.
Chapter 1: ColdFusion Tags 3
CFML Tag Summary (Continued)
CFML Tag Description
CFFORM Builds an input form and performs client-side input
validation.
CFFTP Permits FTP file operations.
CFGRID Used in CFFORM to create a grid control for tabular data.
CFGRIDCOLUMN Used in CFFORM to define the columns used in a CFGRID.
CFGRIDROW Used with CFGRID to define a grid row.
CFGRIDUPDATE Performs updates directly to ODBC data source from
edited grid data.
CFHEADER Generates HTTP headers.
CFHTMLHEAD Writes text, including HTML, to the HEAD section of a
specified page.
CFHTTP Used to perform GET and POST to upload files or post a
form, cookie, query, or CGI variable directly to a specified server.
CFHTTPPARAM Used with CFHTTP to specify parameters necessary for a
CFHTTP POST operation.
CFIF/CFELSEIF/CFELSECFIF/CFELSEIF/CFELSE Used to create IF-THEN-ELSE constructs.
CFIMPERSONATE Allows you to impersonate a user defined in a security
context defined in Advanced Security.
CFINCLUDE Embeds references to ColdFusion pages.
CFINDEX Used to create Verity search indexes.
CFINPUT Used in CFFORM to create input elements such as radio
buttons, checkboxes, and text entry boxes.
CFINSERT Inserts records in an ODBC data source.
CFLDAP Provides access to LDAP directory servers.
CFLOCATION Opens a ColdFusion page or HTML file.
CFLOCK Ensures data integrity and synchronizes the execution of
CFML code.
CFLOOP Repeats a set of instructions based on a set of conditions.
CFMAIL Assembles and posts an email message.
4 CFML Language Reference
CFML Tag Summary (Continued)
CFML Tag Description
CFMAILPARAM Attaches a file or adds a header to an email message.
CFMODULE Invokes a custom tag for use in your ColdFusion
application pages.
CFOBJECT Creates and uses COM, CORBA, or JAVA objects.
CFOUTPUT Displays output of database query or other operation.
CFPARAM Defines a parameter and its initial default value.
CFPOP Retrieves messages from a POP mail server.
CFPROCESSINGDIRECTIVE Suppresses extraneous white space, and other
output.
CFPROCPARAM Specifies parameter information for a stored procedure.
CFPROCRESULT Specifies a result set name that other ColdFusion tags use
to access the result set from a stored procedure.
CFQUERY Passes SQL to a database.
CFQUERYPARAM Reads, writes, and deletes keys and values in the system
registry.
CFREGISTRY Reads, writes, and deletes keys and values in the system
registry.
CFREPORT Embeds a Crystal Reports report.
CFRETHROW Rethrows the currently active exception.
CFSCRIPT Encloses a set of CFScript statements.
CFSEARCH Executes searches against data indexed in Verity
collections using CFINDEX.
CFSELECT Used in CFFORM to create a drop-down list box form
element.
CFSERVLET Executes a Java servlet on a JRun engine.
CFSERVLETPARAM Used to pass data to the Java servlet. CFSERVLETPARAM
is a child tag of CFSERVLET.
CFSET Defines a variable.
CFSETTING Define and control a variety ColdFusion settings.
Chapter 1: ColdFusion Tags 5
CFML Tag Summary (Continued)
CFML Tag Description
CFSILENT Suppresses all output that is produced by the CFML
within the tag’s scope.
CFSLIDER Used in CFFORM to create a slider control element.
CFSTOREDPROC Specifies database connection information and identifies
the stored procedure to be executed.
CFSWITCH/CFCASE/CFDEFAULTCASE Evaluates a passed expression and passes control to the
CFCASE tag that matches the expression result.
CFTABLE Builds a table.
CFTEXTINPUT Places a single-line text entry box in a CFFORM.
CFTHROW Raises a developer-specified exception.
CFTRANSACTION Groups CFQUERYs into a single transaction; performs
rollback processing.
CFTREE Used in CFFORM to create a tree control element.
CFTREEITEM Used with CFTREE to populate a tree control element in a
CFFORM.
CFTRY/CFCATCH Allows developers to catch and process exceptions in
ColdFusion pages.
CFUPDATE Updates rows in a database data source.
CFWDDX Serializes and de-serializes CFML data structures to the
XML-based WDDX format.
New Tags in ColdFusion 4.5
CFEXECUTE CFQUERYPARAM
CFHTTPPARAM CFRETHROW
CFIMPERSONATE CFSERVLET
CFMAILPARAM CFSERVLETPARAM
CFPROCESSINGDIRECTIVE CFSILENT
6 CFML Language Reference
ColdFusion Forms Tags
CFAPPLET CFINPUT
CFFORM CFSELECT
CFGRID CFSLIDER
CFGRIDCOLUMN CFTEXTINPUT
CFGRIDROW CFTREE
CFGRIDUPDATE CFTREEITEM
Database Manipulation Tags
CFINSERT CFQUERYPARAM
CFPROCPARAM CFSTOREDPROC
CFPROCRESULT CFTRANSACTION
CFQUERY CFUPDATE
Data Output Tags
CFCOL CFOUTPUT
CFCONTENT CFTABLE
CFHEADER
Exception Handling Tags
CFERROR
CFRETHROW
CFTHROW
CFTRY/CFCATCH
Chapter 1: ColdFusion Tags 7
Extensibility Tags
CFCOLLECTION CFSEARCH
CFEXECUTE CFSERVLET
CFINDEX CFSERVLETPARAM
CFOBJECT CFWDDX
CFREPORT
File Management Tags
CFDIRECTORY
CFFILE
Flow-Control Tags
CFABORT CFLOOP
CFBREAK CFSWITCH/CFCASE/CFDEFAULTCASE
CFEXECUTE CFTHROW
CFIF/CFELSEIF/CFELSE CFTRY/CFCATCH
CFLOCATION
Internet Protocol Tags
CFFTP CFMAIL
CFHTTP CFMAILPARAM
CFHTTPPARAM CFPOP
CFLDAP
8 CFML Language Reference
Java Servlet and Java Object Tags
CFOBJECT CFSERVLETPARAM
CFSERVLET
Variable Manipulation Tags
CFCOOKIE CFSCRIPT
CFPARAM CFSET
Web Application Framework Tags
CFAPPLICATION CFERROR
CFASSOCIATE CFLOCK
Other Tags
CFAUTHENTICATE
CFASSOCIATE CFREPORT
CFCACHE CFSETTING
CFHTMLHEAD CFSILENT
CFINCLUDE CFWDDX
CFLOCK
Chapter 1: ColdFusion Tags 9
CFABORT
The CFABORT tag stops processing of a page at the tag location. ColdFusion simply returns everything that was processed before the CFABORT tag. CFABORT is often used with conditional logic to stop processing a page because of a particular condition.
Syntax <CFABORT SHOWERROR="text">
SHOWERROR
Optional. Specify the error you want to display when CFABORT executes. This error message appears in the standard ColdFusion error page.
Usage When combining CFABORT and CFERROR, remember that CFERROR is meant to
redirect output to a specified page. CFABORT is intended to halt processing immediately.
If the CFABORT tag does not contain a SHOWERROR attribute value, processing stops immediately and the page contents are shown all the way up to the line containing the CFABORT tag.
When using CFABORT with SHOWERROR by itself (that is without defining an error page using CFERROR) page processing stops once the CFABORT tag is reached and the message defined in SHOWERROR is displayed to the client.
If you have a page in which you’ve defined both an error page using CFERROR and a CFABORT tag using the SHOWERROR attribute, ColdFusion redirects output to the error page specified in the CFERROR tag.
Example <!--- this example demonstrates the use of CFABORT
to stop the processing of a CFLOOP. Note that in the second example, where CFABORT is used, the result never appears --->
<HTML> <HEAD> <TITLE>CFABORT Example</TITLE> </HEAD> <BODY bgcolor=FFFFFF>
<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>
<CFOUTPUT>
10 CFML Language Reference
<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>
Chapter 1: ColdFusion Tags 11
CFAPPLET
Used in a CFFORM, CFAPPLET allows you to reference custom Java applets that have been previously registered using the ColdFusion Administrator.
To register a Java applet, open the ColdFusion Administrator and click the Applets button.
Syntax <CFAPPLET APPLETSOURCE="applet_name"
NAME="form_variable_name" HEIGHT="pixels" WIDTH="pixels" VSPACE="pixels" HSPACE="pixels" ALIGN="alignment" NOTSUPPORTED="text" param_1="value" param_2="value" param_n="value">
APPLETSOURCE
Required. The name of the registered applet.
NAME
Required. The form variable name for the applet.
HEIGHT
Optional. The height in pixels.
WIDTH
Optional. The width in pixels.
VSPACE
Optional. Space above and below applet in pixels.
HSPACE
Optional. Space on each side of the applet in pixels.
ALIGN
Optional. Alignment. Valid entries are:
Left
Right
Bottom
To p
Te x tTo p
Middle
12 CFML Language Reference
AbsMiddle
Baseline
AbsBottom
NOTSUPPORTED
Optional. The text you want to display if the page containing a Java applet-based 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 appears:
<B>Browser must support Java to <BR> view ColdFusion Java Applets!</B>
param
n
Optional. The valid name of a registered parameter for the applet. Specify a parameter only if you want to override parameter values already defined for the applet using the ColdFusion Administrator.
Usage Since 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 directly 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>
Chapter 1: ColdFusion Tags 13
CFAPPLICATION
Defines 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, used to enable session variables and to set timeouts for both session and application variables. Session and application variables are stored in memory.
Syntax <CFAPPLICATION NAME="Name"
CLIENTMANAGEMENT="Yes/No" CLIENTSTORAGE="Storage Type" SETCLIENTCOOKIES="Yes/No" SESSIONMANAGEMENT="Yes/No" SESSIONTIMEOUT=#CreateTimeSpan(days, hours, minutes, seconds)# APPLICATIONTIMEOUT=#CreateTimeSpan(days, hours, minutes, seconds)# SETDOMAINCOOKIES="Yes/No"
>
NAME
The name you want to give your application. This name can be up to 64 characters long. Required for application and session variables to work. Optional for client variables.
CLIENTMANAGEMENT
Optional. Yes or No. Enables client variables. Default is No.
CLIENTSTORAGE
Optional. Specifies the mechanism for storing client variables:
datasourcename — ColdFusion stores client variables in the specified 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.
Registry — ColdFusion stores client variables in the system registry. This is the
default.
Cookie — ColdFusion stores client variables on the client machine in a cookie.
Storing client data in a cookie is scalable to large numbers of clients, but this storage mechanism has some limitations. Chief among them is that if the client turns off cookies in the browser, client variables won’t work.
SETCLIENTCOOKIES
Optional. 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.
14 CFML Language Reference
SESSIONMANAGEMENT
Optional. Yes or No. Yes enables session variables. Default is No.
SESSIONTIMEOUT
Optional. Enter the CreateTimeSpan function and the values you want in days, hours, minutes, and seconds, separated by commas to specify the lifespan of any session variables that are set. The default value is specified in the Variables page of the ColdFusion Administrator.
APPLICATIONTIMEOUT
Optional. Enter the CreateTimeSpan function and the values you want in days, hours, minutes, and seconds, separated by commas to specify the lifespan of any application variables that are set. The default value is specified in the Variables page of the ColdFusion Administrator.
SETDOMAINCOOKIES
Optional. Yes or No. Sets the CFID and CFTOKEN cookies for an entire domain not just a single host. Applications that are running on clusters must set this value to Yes. Th e def ault is No.
Usage CFAPPLICATION is typically used in the Application.cfm file to set defaults for a
specific ColdFusion application.
CFAPPLICATION enables application variables unless they have been disabled in the ColdFusion Administrator. Using the SESSIONMANAGEMENT attribute to enable session variables is also overridden by the Administrator. See Administering ColdFusion Server for information about the ColdFusion Administrator.
Server, Application, and Session Variables
Whenever you display, set, or update variables in the server, application, and session scopes, you should use the CFLOCK tag with the SCOPE attribute. For server variables, specify the "Server" scope. For application variables, specify the "Application" scope. For session variables, specify the "Session" scope. See CFLOCK for information about locking server, application, and session scopes.
If you are running ColdFusion on a cluster, you must specify either Cookie or a data source name for CLIENTSTORAGE; you cannot specify Registry.
Example <!-------------------------------------------------------------
This example shows how CFLOCK can be used to guarantee the consistency of data updates to variables in the Application,
Server, and Session scopes. You should copy the following code into an Application.cfm
file in the snippets directory.
---------------------------------------------------------------> <HTML> <HEAD>
<title>Define Session and Application Variables</title>
</HEAD>
<BASEFONT FACE="Arial, Helvetica" SIZE=2>
Chapter 1: ColdFusion Tags 15
<BODY bgcolor="#FFFFD5">
<H3>CFAPPLICATION Example</H3>
<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 that will be used by E-Turtleneck. Use the session scope for the session variables.
---------------------------------------------------------------> <CFLOCK SCOPE="Session" TIMEOUT="30" TYPE="Exclusive">
<CFIF NOT IsDefined("session.size")>
<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.
-------------------------------------------------------------------> <CFLOCK SCOPE="Application" TIMEOUT="30" TYPE="Exclusive">
<CFIF NOT IsDefined("application.number")>
<CFSET application.number = 1> </CFIF>
</CFLOCK> <CFLOCK SCOPE="Application" TIMEOUT="30" TYPE="ReadOnly">
<CFOUTPUT> E-Turtleneck is proud to say that we have sold #application.number# turtlenecks to date. </CFOUTPUT>
</CFLOCK> <!--- End of Application.cfm --->
16 CFML Language Reference
CFASSOCIATE
The CFASSOCIATE tag allows sub-tag data to be saved with the base tag. This applies to custom tags only.
Syntax <CFASSOCIATE BASETAG="tagname"
DATACOLLECTION="collectionname">
BASETAG
Specifies the name of the base tag.
DATACOLLECTION
Optional. Specifies the name of the structure in which the base tag stores sub-tag data. The default is AssocAttribs.
Usage Call this tag within a sub-tag to save sub-tag data in the base tag.
ColdFusion saves sub-tag attributes in a structure whose default name is AssocAttribs. Use the DataCollection attribute to specify a non-default structure name. Specify a non-default structure name when the base tag can have multiple sub tags and you want to segregate sub-tag 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"> ...
Chapter 1: ColdFusion Tags 17
CFAUTHENTICATE
The CFAUTHENTICATE tag authenticates a user, setting a security context for the application. See the descriptions of the functions IsAuthenticated and
AuthenticatedContext.
Syntax <CFAUTHENTICATE SECURITYCONTEXT="context"
USERNAME="user ID" PASSWORD="password" SETCOOKIE="yes/no" THROWONFAILURE="yes/no">
SECURITYCONTEXT
Required. Security context with which the specified user is authenticated. This context must have been previously defined in the security system.
USERNAME
Required. User to be authenticated.
PASSWORD
Required. Password for the user.
SETCOOKIE
Optional. Default is Yes. Indicates whether ColdFusion sets a cookie to contain authentication information. This cookie is encrypted and its contents include user name, security context, browser remote address, and the HTTP user agent.
THROWONFAILURE
Optional. Default is Yes. Indicates whether ColdFusion throws an exception (of type SECURITY) if authentication fails.
Usage Code this tag in the Application.cfm file to set a security context for your application.
Call the IsAuthenticated function to determine if the user has been authenticated. If you specify No for SETCOOKIE, you must call CFAUTHENTICATE for every page in the application (perhaps in an Application.cfm file).
If you specify THROWONFAILURE=Yes, you can enclose CFAUTHENTICATE in a CFTRY/CFCATCH block to handle possible exceptions programmatically.
Example <!--- This example shows the use of CFAUTHENTICATE
in an Application.cfm file ---> <CFIF NOT IsAuthenticated()> <CFTRY> <CFAUTHENTICATE SECURITYCONTEXT="Allaire" USERNAME=#user# PASSWORD=#pwd#> <CFCATCH TYPE="Security"> <!--- the message to display ---> <H3>Authentication error</H3>
18 CFML Language Reference
<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"> ...
Chapter 1: ColdFusion Tags 19
CFBREAK
Used to break out of a CFLOOP. See Breaking out of a loop, later in this chapter, for more information.
Syntax <CFBREAK>
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 Number </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 desired 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 desired value is found, then use CFBREAK to exit the query ---> <CFLOOP QUERY="GetCourses">
<CFIF GetCourses.Number 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>
20 CFML Language Reference
CFCACHE
CFCACHE allows you to speed up pages considerably in cases where the dynamic content doesn’t need to be retrieved each time a user accesses the page. To accomplish this, it creates temporary files that contain the static HTML returned from a particular run of the ColdFusion page.
You can use CFCACHE for simple URLs and URLs that contain URL parameters.
Syntax <CFCACHE
ACTION="action"
PROTOCOL="protocol name"
TIMEOUT="timeout date-time"
DIRECTORY="directory name for map file"
CACHEDIRECTORY="directory name for cached pages"
EXPIREURL="wildcarded URL reference"
PORT= "port-number">
ACTION
Optional. Specifies one of the following:
CACHE — Specifies server-side caching. The default is CACHE.
FLUSH — Refresh the cached page. If you specify FLUSH, you can also specify
the DIRECTORY and EXPIREURL attributes.
CLIENTCACHE —Specifies browser caching.
OPTIMAL—Specifies optimal caching through a combination of server-side
and browser caching.
See the Usage section for more information.
PROTOCOL
Optional. Specifies the protocol used to create pages from cache. Specify either
HTTP:// or HTTPS://. The default is HTTP://.
TIMEOUT
Optional. DateTime that specifies the oldest acceptable cached page. If the cached
page is older than the specified datetime, ColdFusion refreshes the page. By
default, ColdFusion uses all cached pages. For example, if you want a cached file
to be no older than 4 hours, code the following:
<CFCACHE TIMEOUT="#DateAdd("h", "-4", Now() )#">
DIRECTORY
Optional. Used with ACTION=FLUSH. Specifies the fully qualified path of a
directory containing the cfcache.map to be used when ACTION=FLUSH. The
default is the directory of the current page.
Chapter 1: ColdFusion Tags 21
CACHEDIRECTORY
Optional. Specifies the fully qualified path of the directory where the pages are to
be cached. The default is the directory of the current page.
EXPIREURL
Optional. Used with ACTION=FLUSH. EXPIREURL takes a wildcarded URL
reference 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".
PORT
Optional. The port number of the web server from which the page is being
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.
Usage In its simplest form, all you need to do is code <CFCACHE> at the top of a page for it to
be cached.
With the ACTION attribute, you can specify server-side caching, browser caching, or a combination of server-side and browser caching. The advantage of browser caching is that it takes no ColdFusion resources because the browser stores the pages in its own cache, thus, improving performance. The advantage of using a combination of the two forms of caching is that it optimizes performance; if the browser cache times out, the server can retrieve the cached data from its own cache.
In addition to the cached files themselves, CFCACHE uses a mapping file to control caching. It is named cfcache.map and 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 "foo.cfm", which can be invoked with or without URL parameters. The cfcache.map file entries for foo.cfm will look like this:
[foo.cfm]
Mapping=C:\InetPub\wwwroot\dir1\CFCBD.tmp
SourceTimeStamp=08/31/1999 08:59:04 AM
[foo.cfm?x=5]
Mapping=C:\InetPub\wwwroot\dir1\CFCBE.tmp
SourceTimeStamp=08/31/1999 08:59:04 AM
[foo.cfm?x=9]
Mapping=C:\InetPub\wwwroot\dir1\CFCBF.tmp
SourceTimeStamp=08/31/1999 08:59:04 AM
The cfcache.map file in a given directory stores mappings for that directory only. Any time the timestamp of the underlying page changes, ColdFusion updates the cache file for that URL only. ColdFusion uses the SourceTimeStamp field to determine if the currently cached file is up to date or needs to be rebuilt.
22 CFML Language Reference
You can refresh the cache in the following ways:
TIMEOUT attribute — ColdFusion tests the timestamp of the cached file
against the TIMEOUT attribute. If the cached file’s timestamp is older than TIMEOUT, the old file is deleted and a new one created. You can use fixed dates if necessary, but it's preferable to use relative dates. This is the preferred technique and it 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.
Manually — Manually or programmatically (using CFFILE) delete the .tmp files.
This is not recommended.
Note the following regarding CFCACHE:
CFCACHE requires that ColdFusion Server "simultaneous requests" be greater
than 1. When a cache file is generated, the requested page requires two connections to satisfy the request. When a cached file is found, only one request is required.
Debug settings have no effect on CFCACHE unless the template explicitly turns
it on. When generating a cached file, CFCACHE uses
SHOWDEBUGOUTPUT="NO">
.
<CFSETTING
ColdFusion does not cache pages that are dependent on anything other than
URL parameters.
To use CFCACHE with the Secure Sockets Layer (SSL), specify
PROTOCOL="http://". If you need to use SSL, you must run ColdFusion as a
desktop application. Please note, however, Allaire strongly recommends that you run the ColdFusion Server as a service. For more details about using SSL, see Knowledge Base article #1096 at http://www.allaire.com/Support/
KnowledgeBase/SearchForm.cfm.
If a template returns an error for any reason, the error page gets cached.
Example <!--- This example will produce as many cached files as there
are possible URL parameter permutations. ---> <CFCACHE TIMEOUT="#DateAdd("h", "-4", Now() )#"> <HTML> <HEAD> <TITLE>CFCACHE Example</TITLE> </HEAD> <BODY> <H1>CFCACHE Example</H1>
<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>
Chapter 1: ColdFusion Tags 23
CFCOL
Defines table column header, width, alignment, and text. Only used inside a CFTABLE.
Syntax <CFCOL HEADER="text"
WIDTH="number"
ALIGN="position"
TEXT="text">
HEADER
The text to use for the column’s header.
WIDTH
The width of the column in characters (the default is 20). If the length of the data
displayed exceeds the width value, the data is truncated to fit.
ALIGN
Column alignment, Left, Right, or Center.
TEXT
Double-quote delimited text that determines what displays in the column. The
rules for the text attribute are identical to the rules for CFOUTPUT sections,
meaning that it can consist of a combination of literal text, HTML tags, and query
record set field references. This means you can embed hyperlinks, image
references, and even input controls within table 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 ---> <CFTABLE QUERY="GetEmployees" STARTROW="1" COLSPACING="3" HTMLTABLE> <!--- each CFCOL tag sets the width of a column in the table,
24 CFML Language Reference
as well as specifying the header information and the text/CFML with which to fill the cell --->
<CFCOL HEADER = "<B>ID</B>"
ALIGN = "Left" WIDTH = 2 TEXT = "#Emp_ID#">
<CFCOL HEADER = "<B>Name/Email</B>"
ALIGN = "Left" WIDTH = 15
TEXT = "<a href=’mailto:#Email#’>#FirstName# #LastName#</A>">
<CFCOL HEADER = "<B>Phone Number</B>"
ALIGN = "Center" WIDTH = 15
</CFTABLE>
</BODY> </HTML>
TEXT = "#Phone#">
Chapter 1: ColdFusion Tags 25
CFCOLLECTION
The CFCOLLECTION tag allows you to create and administer Verity collections.
Syntax <CFCOLLECTION ACTION="action"
COLLECTION="collection"
PATH="implementation directory"
LANGUAGE="language">
ACTION
Required. Specifies the action to perform:
CREATE — Creates a new collection using the specified path and optionally
specified language.
REPAIR — Fixes data corruption in the collection.
DELETE — Destroys the collection.
OPTIMIZE — Purges and reorganizes data for efficiency.
MAP — Assigns an alias to an existing Verity collection.
COLLECTION
Required. Specifies a collection name or an alias if the ACTION is MAP.
PATH
Required for CREATE and MAP. Specifies a path to the Verity collection. The effect
of the PATH attribute depends on the ACTION that you specify.
ACTION What happens?
CREATE
CFCOLLECTION creates a directory for the use of Verity. The directory path is composed of the directory path specified in the PATH attribute with the name specified in the COLLECTION attribute appended to it. Thus, the full directory path is "path_name\collection_name\." For example, if the path name is "C:\Col\," and the collection name is "myCollection," the full directory path is "C:\Col\myCollection\."
MAP
The MAP action provides a name with which ColdFusion can reference an existing collection. This name is specified with the COLLECTION attribute. It is an alias for the collection, which can be used in CFINDEX, and to re-instate a collection after you have re-installed ColdFusion. The directory path specified with the PATH attribute is the full path name of the Verity directory. Therefore, to reference the directory created in the previous example, specify "C:\Col\myCollection\."
26 CFML Language Reference
LANGUAGE
Optional for CREATE. To use the LANGUAGE attribute you must have the
ColdFusion International Search Pack installed. Valid entries are:
English (default)
German
Finnish
French
Danish
Dutch
Italian
Norwegian
Portuguese
Spanish
Swedish
Usage CFCOLLECTION works at the collection level only. To add content to a collection, use
CFINDEX.
Note the following regarding mapped collections:
Mapping allows you to assign an alias to a Verity 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.
Example <!--- This example shows the basic functionality
of the CFCOLLECTION tag (create, repair, optimize, delete) ---> <HTML> <HEAD>
<TITLE>CFCOLLECTION</TITLE> </HEAD> <BODY bgcolor=silver> <H3>CFCOLLECTION</h3>
<!--- see if a collection name has been specificied ... ---> <CFIF IsDefined("form.CollectionName") AND IsDefined("form.CollectionAction")>
<CFIF form.CollectionName is not "">
<CFOUTPUT> <CFSWITCH EXPRESSION=#FORM.CollectionAction#> <CFCASE VALUE="Create"> <CFCOLLECTION ACTION="CREATE"
Chapter 1: ColdFusion Tags 27
COLLECTION="#FORM.CollectionName#" PATH="C:\CFUSION\Verity\Collections\"> <H3>Collection created.</H3> </CFCASE> <CFCASE VALUE="Repair"> <CFCOLLECTION ACTION="REPAIR" COLLECTION="#FORM.CollectionName#"> <H3>Collection repaired.</H3> </CFCASE> <CFCASE VALUE="Optimize"> <CFCOLLECTION ACTION="OPTIMIZE" COLLECTION="#FORM.CollectionName#"> <H3>Collection optimized.</H3> </CFCASE> <CFCASE VALUE="Delete"> <CFCOLLECTION ACTION="DELETE" COLLECTION="#FORM.CollectionName#"> <H3>Collection deleted.</H3> </CFCASE>
...
</CFSWITCH>
28 CFML Language Reference
CFCONTENT
Defines the MIME type returned by the current page. Optionally, allows you to specify the name of a file to be returned with the page.
Note The ColdFusion Server Basic security settings may prevent CFCONTENT
from executing. These settings are managed using the ColdFusion Administrator Basic Security page. In order for CFCONTENT to execute, it needs to be enabled on the Basic Security page. Please refer to Administering ColdFusion Server for more information about securing ColdFusion tags.
Syntax <CFCONTENT TYPE="file_type"
DELETEFILE="Yes/No"
FILE="filename"
RESET="Yes/No">
TYPE
Required. 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 attribute only applies if you are specifying a file with the FILE attribute.
FILE
Optional. Denotes the name of the file being retrieved.
RESET
Optional. Yes or No. Yes discards any output that precedes the call to
CFCONTENT. No preserves the output that precedes the call. Defaults to Yes. The
RESET and FILE attributes are mutually exclusive. If you specify a file, the RESET
attribute has no effect. See Note.
Note You should consider setting RESET to "No " if you are calling
CFCONTENT from a custom tag and do not want the tag to have the side effect of discarding the current page whenever it is called from another application or custom tag.
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 </TITLE> </HEAD>
Chapter 1: ColdFusion Tags 29
<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
<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 text.</P> <P>RESET = "Yes ": 123<CFCONTENT type="text/html" reset= "Yes ">456</P> <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>
output. --->
30 CFML Language Reference
CFCOOKIE
Defines cookie variables, including expiration and security options.
Syntax <CFCOOKIE NAME="cookie_name"
VALUE="text"
EXPIRES="period"
SECURE="Yes/No"
PATH="urls"
DOMAIN=".domain">
NAME
Required. The name of the cookie variable.
VALUE
Optional. The value assigned to the cookie variable.
EXPIRES
Optional. 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’s browser.
SECURE
Optional. Indicates the variable has to transmit securely. If the browser does not
support Secure Socket Layer (SSL) security, the cookie is not sent.
PATH
Optional. Specifies the subset of URLs within the specified domain to which this
cookie applies:
PATH="/services/login"
Separate multiple entries with a semicolon ( ; ).
DOMAIN
Specifies the domain for which the cookie is valid and to which the cookie content
can be sent. An explicitly specified domain must always start with a dot. This can
be a subdomain, in which case the valid domains will be any domain names
ending in this string.
For domain names ending in country codes (such as
specification must contain at least three periods, for example,
.jp, .us), the subdomain
.mongo.stateu.us.
In the case of special top level domains, only two periods are needed, as in
.allaire.com.
When specifying a PATH value, you must include a valid DOMAIN.
Separate multiple entries with a semicolon ( ; ).
Usage Cookies written with CFCOOKIE do not get written to the cookies.txt file until the
browser session ends. Until the browser is closed, the cookie resides in memory. If you
Chapter 1: ColdFusion Tags 31
do not have an EXPIRES attribute in a CFCOOKIE, the cookie set exists only as long as the client browser is open. When the browser is closed, the cookie expires. It is never written to the cookies.txt file.
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 email address --->
<CFLOOP QUERY="GetAOLUser">
<CFIF FindNoCase("aol.com", Email, 1) is not 0>
<CFCOOKIE NAME="LastAOLVisitor" VALUE="#Email#" EXPIRES="NOW" >
</CFIF> </CFLOOP>
<!--- If the timeVisited cookie is not set, set a value --->
<CFIF IsDefined("Cookie.TimeVisited") is False>
<CFCOOKIE NAME="TimeVisited" VALUE="#Now()#" EXPIRES="10">
</CFIF> </CFIF>
32 CFML Language Reference
<!--- 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>
Chapter 1: ColdFusion Tags 33
CFDIRECTORY
Use the CFDIRECTORY tag to handle all interactions with directories.
Note The ColdFusion Server Basic security settings may prevent
CFDIRECTORY from executing. These settings are managed using the ColdFusion Administrator Basic Security page. In order for CFDIRECTORY to execute, it needs to be enabled on the Basic Security page.
If you write ColdFusion applications designed to run on a server that is used by multiple customers, you need to consider the security of the files and directories that could be uploaded or otherwise manipulated by CFDIRECTORY. Please refer to Administering ColdFusion Server for more information about securing ColdFusion tags.
Syntax <CFDIRECTORY ACTION="directory action"
DIRECTORY="directory name"
NAME="query name"
FILTER="list filter"
MODE="permission"
SORT="sort specification"
NEWDIRECTORY="new directory name">
ACTION
Optional. Defines the action to be taken with directory(ies) specified in
DIRECTORY. Valid entries are:
List (default)
Create
Delete
Rename.
DIRECTORY
Required for all ACTIONs. The name of the directory you want the action to be
performed against.
NAME
Required for ACTION="List". Ignored for all other actions. Name of output query
for directory listing.
FILTER
Optional for ACTION="List". Ignored for all other actions. File extension filter to
be applied to returned names, for example:
applied at a time.
*.cfm. Only one mask filter can be
MODE
34 CFML Language Reference
Optional. Used with ACTION="Create" to define the permissions for a directory
on Solaris or HP-UX. Ignored in Windows. Valid entries correspond 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 all, owner read/write permission, group and other read/write
permissions.
MODE=666
Assigns read/write permissions for owner, group, and other.
MODE=777
Assigns read, write, and execute permissions for all.
SORT
Optional for ACTION="List". Ignored for all other actions. List of query columns to
sort directory listing by. Any combination of columns from query output can be
specified in comma separated list. ASC or DESC can be specified as qualifiers for
column names. ASC is the default. For example:
SORT="dirname ASC, filename2 DESC, size, datelastmodified"
NEWDIRECTORY
Required for ACTION="Rename". Ignored for all other actions. The new name of
the directory specified in the DIRECTORY attribute.
ACTION=LIST
When using the ACTION=LIST, CFDIRECTORY returns five result columns you can reference in your CFOUTPUT:
Name – Directory entry name.
Size – Size of directory entry.
Type – File type: File or Dir for File or Directory.
DateLastModified – Date an entry was last modified.
Attributes – File attributes, if applicable.
Mode – (Solaris and HP-UX only) The octal value representing the permissions
setting for the specified directory. For information about octal values, refer to the UNIX man pages for the
You can use the following result columns in standard CFML expressions, preceding the result column name with the name of the query:
#mydirectory.Name# #mydirectory.Size# #mydirectory.Type# #mydirectory.DateLastModified# #mydirectory.Attributes# #mydirectory.Mode#
chmod shell command.
Chapter 1: ColdFusion Tags 35
Example <!----------------------------------------------------------------------
This example shows the use of CFDIRECTORY to display the contents of the snippets directory in CFDOCS.
-----------------------------------------------------------------------> <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:"
<CFCOL HEADER="SIZE:"
</CFTABLE>
TEXT="#Name#">
TEXT="#Size#">
</BODY> </HTML>
36 CFML Language Reference
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.
Syntax <CFERROR
TYPE="Request" or "Validation" or "Monitor" or "Exception"
TEMPLATE="template_path"
MAILTO="email_address"
EXCEPTION=”exception_type”>
TYPE
Required. The type of error that this custom error page is designed to handle:
Specify Exception to handle exceptions.
Specify Validation to handle data input validation errors that occur when
submitting a form. A validation error handler is only useful if placed inside the
Application.cfm file.
Specify Monitor to set up an exception monitor.
Specify Request to handle errors that occur during the processing of a page.
Request is the default.
See the table under CFERROR Error Variables for information about the variables
and other constructs available from the templates used to handle each type of
error.
TEMPLATE
Required. The relative path to the custom error handling page. The following table describes the template to use for each type of error.
Types and Their Corresponding Custom Error Pages
Typ e Custom Error Page
Exception
An exception-handling template that is dynamically invoked by the CFML language processor when it detects an unhandled exception condition. Exception-handling templates may be specified as part of an application, via the <CFERROR TYPE="Exception"> tag, or may be set via the ColdFusion Administrator.
$QH[FHSWLRQKDQGOLQJWHPSODWHFDQXVHWKHIXOO UDQJHRI&)0/WDJVPDNLQJLWVLJQLILFDQWO\PRUH SRZHUIXOWKDQ&)(55257<3(
This template also has access to the error variables in the table under CFERROR Error Variables.
"
5HTXHVW"!
Chapter 1: ColdFusion Tags 37
Types and Their Corresponding Custom Error Pages (Continued)
Typ e Custom Error Page
Request
This template can include only the error variables described in the table under CFERROR Error
LVXVHIXO
Validation
Variab les and cannot include CFML tags. It
DVDEDFNXSHUURUKDQGOHUIRUVLWHVZLWKKLJK XVHULQWHUIDFHUHTXLUHPHQWV
A validation error handler. It handles data input validation errors that occur when submitting a form. It is useful only if placed inside the Application.cfm file.
Monitor
An exception-monitoring template is dynamically invoked by the CFML language processor when it first detects an exception condition, before it searches for <CFTRY>/<CFCATCH> or <CFERROR> handlers for the exception.
Exception-monitoring templates are useful for monitoring and debugging exception handling within complex applications.
MAILTO
Optional. The email address of the administrator who should be notified of the
error. This value is available to your custom error page using the MailTo property
of the error object, such as #Error.MailTo#.
EXCEPTION
Required if the type is specified as Exception or Monitor. The type of exception.
Usage The CFERROR tag is normally used to customize the error messages for all the pages in
an application. As a result, you generally embed it in the more information about the
Application.cfm file, refer to Developing Web
Applications with ColdFusion.
To help ensure that error pages display successfully, pages you specify with CFERROR should not be encoded with the
cfencode utility.
Application.cfm file. For
CFERROR Error Variables
The exception-handling template specified in the TEMPLATE attribute of the CFERROR tag may contain one or more error variables, which will be substituted by ColdFusion when an error is displayed.
38 CFML Language Reference
Error Variables for Request, Exception, and Monitor Types
The following error variables are available when CFERROR specifies TYPE="Request", TYPE="Exception" or TYPE="Monitor":
Variables for Request, Exception, and Monitor Types
Error Variable Description
Error.Diagnostics
Error.MailTo
Detailed error diagnostics from ColdFusion Server.
Email address of administrator who should be notified (corresponds to the value set in the MAILTO attribute of CFERROR).
Error.DateTime
Error.Browser
Error.GeneratedContent
Error.RemoteAddress
Error.HTTPReferer
Date and time when the error occurred.
Browser that was running when the error occurred.
The failed request’s generated content .
IP address of the remote client.
Page from which the client accessed the link to the page where the error occurred.
Error.Template
Error.QueryString
Page being executed when the error occurred.
URL query string of the client's request.
Note If you have specified TYPE="Exception" or TYPE="Monitor", you
can substitute the prefix CFERROR for Error if you prefer this form; for example, CFERROR.Diagnostics, CFERROR.Mailto or CFERROR.DateTime.
Error pages where TYPE="Validation"
Error variables available when CFERROR uses TYPE="Validation" are as follows:
Custom Error Pages where TYPE="Validation"
Error Variable Description
Error.ValidationHeader
Error.InvalidFields
Error.ValidationFooter
Text for header of validation message.
Unordered list of validation errors that occurred.
Text for footer of validation message.
Chapter 1: ColdFusion Tags 39
Example <!--- 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 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"
TEMPLATE="request_err.cfm"
MAILTO="admin@mywebsite.com">
<!--- 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%> <P>#Error.Diagnostics#<HR width=50%><P>
<LI><B>Please send questions to:</B> <a href="mailto:#Error.MailTo#">#Error.MailTo#</A> </CFOUTPUT> </UL> </BODY> </HTML> --->
40 CFML Language Reference
CFEXECUTE
Enables ColdFusion developers to execute any process on the server machine.
Syntax <CFEXECUTE
NAME=" ApplicationName "
ARGUMENTS="CommandLine Arguments"
OUTPUTFILE="Output file name”
TIMEOUT=”Timeout interval in seconds”>
NAME
Required. The full path name of the application that is to be executed.
Note: On Windows systems, you must specify the extension, for example, .exe, as
part of the application’s name.
ARGUMENTS
Optional. Any command-line arguments that should be passed to the program.
If ARGUMENTS is specified as a string, it is processed as follows:
On Windows systems, the entire string is passed to the Windows process
control subsystem for parsing.
On UNIX, the string is tokenized into an array of arguments. The default 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 systems, the array elements will be concatenated into a string of
tokens, separated by spaces. This string is then passed to the Windows process control subsystem as above.
On UNIX, the elements of the ARGUMENTS array is copied into a
corresponding array of exec() arguments.
OUTPUTFILE
Optional. The file where the output of the program is to be directed. If this is not
specified, the output appears on the page from which it was called.
TIMEOUT
Optional. Indicates how long in seconds the ColdFusion executing thread will wait
for the spawned process. Indicating a timeout of 0 is equivalent to the non-
blocking mode of executing. A very high timeout value is equivalent to a blocking
mode of execution. The default is 0; therefore, the ColdFusion thread spawns a
process and immediately returns without waiting for the process to terminate.
If no output file is specified, and the timeout value is zero, then the program’s
output will be directed to the bit bucket.
Chapter 1: ColdFusion Tags 41
Usage CFEXECUTE is available on Windows NT 4.0 and UNIX platforms. Do not put any
other ColdFusion tags or functions between the start and the end tags of CFEXECUTE. Also, CFEXECUTE tags cannot be nested.
Exception CFEXECUTE throws the following exceptions:
If the application name is not found, an Application File Not Found exception
will be thrown.
If the output file cannot be opened, an Output File Cannot be opened will be
thrown.
If the effective user of the ColdFusion executing thread does not have
permissions to execute the process, a security exception will be thrown.
The time out values must be between 0 and some high number (to be
determined).
Example <!----------------------------------------------------------------------
This example illustrates use of the CFEXECUTE tag.
-----------------------------------------------------------------------> <HTML> <HEAD> <TITLE>CFEXECUTE</TITLE> </HEAD>
<BODY> <H3>CFEXECUTE</H3> <P> This example executes the Windows NT version of the netstat network monitoring program, and places its output in a file.
<CFEXECUTE NAME="C:\WinNT\System32\netstat.exe"
ARGUMENTS="-e"
OUTFILE="C:\Temp\output.txt"
TIMEOUT=”1”>
</CFEXECUTE> </BODY> </HTML>
42 CFML Language Reference
CFEXIT
CFEXIT can be used to:
Abort the processing of the currently executing CFML custom tag.
Exit the template within the currently executing CFML custom tag.
Reexecute a section of code within the currently executing CFML custom tag.
Syntax <CFEXIT METHOD="method">
METHOD
Optional. Specifies one of the following:
ExitTag (default) — Aborts processing of the currently executing CFML custom
tag.
ExitTemplate — Exits the template of the currently executing CFML custom tag.
Loop — Reexecutes the body of the currently executing CFML custom tag.
Usage If a CFEXIT tag is encountered outside the context of a custom tag, for example in the
base page or an included page, the tag acts exactly like CFABORT. CFEXIT can help simplify error checking and validation logic in custom tags.
CFEXIT behaves differently depending on location and execution mode:
METHOD
Location of CFEXIT call Behavior
attribute
ExitTag Base template Terminate processing
Execution mode = Start Continue after end tag
Execution mode = End Continue after end tag
ExitTemplate Base template Terminate processing
Execution mode = Start Continue from first child in body
Execution mode = End Continue after end tag
Loop Base template Error
Execution mode = Start Error
Execution mode = End Continue from first child in body
Chapter 1: ColdFusion Tags 43
Example <!--- This example shows the use of CFEXIT, and
is a read-only example ---> <HTML> <HEAD> <TITLE>CFEXIT Example</TITLE> </HEAD>
<BODY> <H3>CFEXIT Example</H3>
<P>CFEXIT can be used to abort the processing of the currently executing CFML custom tag. Execution will resume immediately 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 of 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">
<CFELSEIF NOT IsDefined("attributes.myValue1")>
<CFELSE>
<CFSET value1 = attributes.myValue1>
<CFSET value2 = attributes.myValue2>
</CFIF> ---> <!--- End MyCustomTag.cfm --->
<!--- And place this code inside your page --->
<!--- <P>The call to the custom tag, and then the result: <CF_myCustomTag
<CFOUTPUT>#result#</cFOUTPUT> --->
<CFEXIT METHOD="ExitTag">
<CFSET caller.result = "Value1 is not defined"> <CFEXIT METHOD="ExitTag">
<CFSET caller.result = value1 + value2>
myvalue2 = 4>
44 CFML Language Reference
<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: <CFEXIT> <P>This text will not be executed due to the existence of the CFEXIT tag above it.
</BODY> </HTML>
Chapter 1: ColdFusion Tags 45
CFFILE
Use the CFFILE tag to handle all interactions with files. The attributes you use with CFFILE depend on the value of the ACTION attribute. For example, if the ACTION is "Write, " ColdFusion expects the attributes associated with writing a text file. See the individual CFFILE topics below for details about which attributes apply to which ACTIONs.
Note The Basic Security settings may prevent CFFILE from executing. These
settings are managed using the Basic Security page in the ColdFusion Administrator. In order for CFFILE to execute, it needs to be enabled on the Basic Security page.
If you write ColdFusion applications designed to run on a server that is used by multiple customers, you need to consider the security of the files that could be uploaded or otherwise manipulated by CFFILE. See Administering ColdFusion Serverfor more information about securing ColdFusion tags.
CFFILE topics
CFFILE ACTION="Upload"
CFFILE ACTION="Move"
CFFILE ACTION="Rename"
CFFILE ACTION="Copy"
CFFILE ACTION="Delete"
CFFILE ACTION="Read"
CFFILE ACTION="ReadBinary"
CFFILE ACTION="Append"
46 CFML Language Reference
CFFILE ACTION attributes
Depending on the value you assign to the ACTION attribute of CFFILE, there are several additional attributes you can set. This table shows which attributes you can use with each CFFILE ACTION.
Attributes Used with CFFILE ACTIONs
ACTION Attributes
Upload ACCEPT
DESTINATION FILEFIELD NAMECONFLICT MODE AT TR I BU TE S
Move SOURCE
DESTINATION AT TR I BU TE S
Rename SOURCE
DESTINATION AT TR I BU TE S
Copy SOURCE
DESTINATION AT TR I BU TE S
Delete FILE
Read FILE
VAR IA BL E
ReadBinary FILE
VAR IA BL E
Write OUTPUT
FILE MODE ADDNEWLINE AT TR I BU TE S
Append OUTPUT
FILE MODE ADDNEWLINE AT TR I BU TE S
Sections that follow describe these values and attributes in greater detail.
Chapter 1: ColdFusion Tags 47
CFFILE ACTION="Upload"
Use CFFILE with the Upload action to upload a file specified in a form field to a directory on the Web server.
Note The MODE attribute applies to ColdFusion on Solaris and HP-UX, only.
Syntax <CFFILE ACTION="Upload"
FILEFIELD="formfield"
DESTINATION="full_path_name"
NAMECONFLICT="behavior"
ACCEPT="mime_type/file_type"
MODE="permission"
ATTRIBUTES="file_attributes">
FILEFIELD
Required. The name of the form field that was used to select the file.
Note: Do not use pound signs (#) to specify the field name.
DESTINATION
Required. The full path name of the destination directory on the Web server where
the file should be saved. A trailing slash must be included in the target directory
when uploading a file. Use the backward slash (\) on Windows ; use the forward
slash (/) on UNIX.
Note: The directory does not need to be beneath the root of the Web server
document directory.
NAMECONFLICT
Optional. Default is error. Determines how the file should be handled if its name
conflicts with the name of a file that already exists in the directory. Valid entries
are:
Error — Default. The file will not be saved, and ColdFusion will stop processing
the page and return an error.
Skip — Neither saves the file nor throws an error. This setting is intended to
allow custom behavior based on inspection of FILE properties.
Overwrite — Replaces an existing file if it shares the same name as the CFFILE
destination.
MakeUnique — Automatically generates a unique filename for the upload. This
name will be stored in the FILE object variable "ServerFile. " You can use this variable to record what name was used when the file was saved.
ACCEPT
Optional. Use to limit what types of files will be accepted. Enter one or more
MIME types, each separated by comma, of the file types you want to accept. For
example, to allow uploads of GIF and Microsoft Word files, enter:
ACCEPT="image/gif, application/msword"
48 CFML Language Reference
Note that the browser uses the file extension to determine file type.
MODE
Optional. Defines permissions for an uploaded file on Solaris or HP-UX. Ignored
in Windows. Valid entries correspond 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 the owner read/write permissions and group/other read permission.
MODE=666
Assigns read/write permissions for owner, group, and other.
MODE=777
Assigns read, write, and execute permissions for all.
ATTRIBUTES
Optional. A comma-delimited list of file attributes to be set on the file being
uploaded. 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 as well as any other attributes, Normal is overridden by whatever other
attribute is specified.
Individual attributes must be specified explicitly. For example, if you specify just
the ReadOnly attribute, all other existing attributes are overwritten.
Examples The following example will create a unique filename if there is a name conflict when
the file is uploaded on Windows:
<CFFILE ACTION="Upload"
FILEFIELD="FileContents"
DESTINATION="c:\web\uploads\"
ACCEPT="text/html"
NAMECONFLICT="MakeUnique">
Note 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. "
Chapter 1: ColdFusion Tags 49
Evaluating the results of a file upload
After a file upload is completed, you can retrieve status information using file upload parameters. This status information includes a wide range of data about the file, such
as the file’s name and the directory where it was saved. File upload status parameters use the "File " prefix, for example, File.ClientDirectory
parameters can be used anywhere other
ColdFusion parameters can be used.
The following file upload status parameters are available after an upload.
File Upload Parameters
Parameter Description
. The file status
AttemptedServerFile
ClientDirectory
ClientFile
ClientFileExt
ClientFileName
ContentSubType MIME content subtype of the saved file.
ContentType MIME content type of the saved file.
DateLastAccessed Date and time the uploaded file was last
File Existed
File Size
Initial name ColdFusion used attempting to save a file, for example, myfile.txt.
Directory location of the file uploaded from
the client’s system.
Name of the file uploaded from the client’s sys­tem.
Extension of the uploaded file on the client’s system without a period, for example, txt not .txt.
Filename without an extension of the uploaded file on the client’s system.
accessed.
Indicates (Yes or No) whether or not the file already existed with the same path.
Size of the uploaded file.
FileWasAppended
File WasOve rwritten
Indicates (Yes or No) whether or not ColdFu­sion appended the uploaded file to an existing file.
Indicates (Yes or No) whether or not ColdFu­sion overwrote a file.
50 CFML Language Reference
File Upload Parameters (Continued)
Parameter Description
File WasRenamed
FileWasSaved
OldFileSize
ServerDirectory
ServerFile
ServerFileExt
ServerFileName
TimeCreated
TimeLastModified
Indicates (Yes or No) whether or not the uploaded file was renamed to avoid a name conflict.
Indicates (Yes or No) whether or not Cold Fusion saved a file.
Size of a file that was overwritten in the file upload operation.
Directory of the file actually saved on the server.
Filename of the file actually saved on the server.
Extension of the uploaded file on the server, without a period, for example, txt not .txt.
Filename, without an extension, of the uploaded file on the server.
Time the uploaded file was created.
Date and time of the last modification to the uploaded file.
UNIX
Examples
Tip Use the File prefix to refer to these parameters, for example,
#File.FileExisted#.
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.)
The following three examples show the use of the MODE attribute for UNIX. The first example creates the file write, group/other=read).
<CFFILE ACTION="Write"
FILE="/tmp/foo"
MODE=644>
This example appends to the specified file and makes permissions read/write (rw) for all.
/tmp/foo with permissions defined as rw-r-r-- (owner=read/
Chapter 1: ColdFusion Tags 51
<CFFILE ACTION="Append"
DESTINATION="/home/tomj/testing.txt"
MODE=666
OUTPUT="Is this a test?">
The next example uploads a file and gives it rwx-rw-rw permissions (owner/group/ other=read/write).
CFFILE ACTION="Upload"
FILEFIELD="fieldname"
DESTINATION="/tmp/program.exe"
MODE=755>
CFFILE ACTION="Move"
The CFFILE MOVE action can be used to move a file from one location on the server to another.
Syntax <CFFILE ACTION="Move"
SOURCE="full_path_name"
DESTINATION="full_path_name"
ATTRIBUTES="file_attributes">
SOURCE
Required. The full path name of the file to move.
DESTINATION
Required. The full path name of the directory to which the file will be moved. If
you do not specify the file name, a trailing slash must be included in the target
when moving a file. Use the backward slash (\) on Windows; use the forward slash
(/) on UNIX.
ATTRIBUTES
Optional. A comma-delimited list of file attributes to be set on the file being
moved. 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 as well as any other attributes, Normal is overridden by whatever other
attribute is specified.
Individual attributes must be specified explicitly. For example, if you specify just
the ReadOnly attribute, all other existing attributes are overwritten.
52 CFML Language Reference
Example The following example moves the keymemo.doc file from the c:\files\upload\
directory to the
<CFFILE ACTION="Move" SOURCE="c:\files\upload\keymemo.doc" DESTINATION="c:\files\memo\">
c:\files\memo\ directory on Windows:
Note On Windows, you must include the backward slash (\) after the
destination directory name if you do not specify a file name. In this example, the specified destination directory is "memo. "
CFFILE ACTION="Rename"
Use CFFILE with the Rename action to rename a file that already exists on the server.
Syntax <CFFILE ACTION="Rename"
SOURCE="full_path_name"
DESTINATION="full_path_name"
ATTRIBUTES="file_attributes">
SOURCE
Required. The full path name of the file to rename.
DESTINATION
Required. The full path name, including the new name, of the file.
ATTRIBUTES
Optional. 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 as well as any other attributes, Normal is overridden by whatever other
attribute is specified.
Individual attributes must be specified explicitly. For example, if you specify just
the ReadOnly attribute, all other existing attributes are overwritten.
Chapter 1: ColdFusion Tags 53
Example The following example renames the file keymemo.doc to oldmemo.doc:
<CFFILE ACTION="Rename"
SOURCE="c:\files\memo\keymemo.doc"
DESTINATION="c:\files\memo\oldmemo.doc">
CFFILE ACTION="Copy"
The CFFILE tag can be used to copy a file from one directory to another on the server.
Syntax <CFFILE ACTION="Copy"
SOURCE="full_path_name"
DESTINATION="full_path_name"
ATTRIBUTES="file_attributes">
SOURCE
Required. The full path name of the file to copy.
DESTINATION
Required. The full path name of the directory where the copy of the file will be
saved. If you do not specify a file name, you must include the trailing slash. On
Windows, use the backward slash (\). On UNIX, use the forward slash (/).
ATTRIBUTES
Optional. A comma-delimited list of file attributes to be set on the file being
copied. 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 as well as any other attributes, Normal is overridden by whatever other
attribute is specified.
Individual attributes must be specified explicitly. For example, if you specify just
the ReadOnly attribute, all other existing attributes are overwritten.
Example The following example saves a copy of the keymemo.doc file in the c:\files\backup\
directory:
<CFFILE ACTION="Copy"
SOURCE="c:\files\upload\keymemo.doc"
DESTINATION="c:\files\backup\">
54 CFML Language Reference
Note On Windows, you must include the backward slash (\) after the
destination directory name if you do not specify a file name. In this example, the specified destination directory is "backup. "
CFFILE ACTION="Delete"
The CFFILE tag can be used to delete a file on the server.
Syntax <CFFILE ACTION="Delete"
FILE="full_path_name">
FILE
Required. The full path name of the file to delete.
Example The following example permanently deletes the specified file:
<CFFILE ACTION="Delete"
FILE="c:\files\upload\#Variables.DeleteFileName#">
CFFILE ACTION="Read"
You can use the CFFILE tag to read an existing text file. The file is read into a dynamic parameter you can use anywhere in the page like any other dynamic parameter. For 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 one of the find and replace functions to modify its contents.
Syntax <CFFILE ACTION="Read"
FILE="full_path_name"
VARIABLE="var_name">
FILE
Required. The full path name of the text file to be read.
VARIABLE
Required. The name of the variable that will contain the contents of the text file
after it has been read.
Example The following example creates a variable named "Message " that will 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
message.txt file in the final Web page:
Chapter 1: ColdFusion Tags 55
<CFOUTPUT>#Message#</CFOUTPUT>
ColdFusion supports a number of powerful functions for manipulating the contents of text files. You can also use variable created by a CFFILE Read operation in ArrayToList and ListToArray functions.
See String Functions and Array Functions for more information about working with strings and arrays.
CFFILE ACTION="ReadBinary"
You can use the CFFILE tag to read an existing 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. If you would like to send it through one of the Web protocols, such as HTTP or SMTP, or store it in a database, you should first convert it to Base 64 (see To Ba s e 6 4 ).
Syntax <CFFILE ACTION="ReadBinary"
FILE="full_path_name"
VARIABLE="var_name">
FILE
Required. The full path name of the file to be read.
VARIABLE
Required. The name of the variable that will contain the contents of the binary file
after it has been read.
Example The following example creates a variable named "aBinaryObj " that will contain the
ColdFusion Server executable.
<CFFILE ACTION="ReadBinary"
FILE="c:\cfusion\bin\cfserver.exe"
VARIABLE="aBinaryObj">
You can then convert the binary file to Base 64 so that you could FTP it to another site for upload.
CFFILE ACTION="Write"
You can use the CFFILE tag to write a text file based on dynamic content. For example, you could create static HTML files from this content or log actions in a text file.
Syntax <CFFILE ACTION="Write"
FILE="full_path_name"
OUTPUT="content"
MODE="permission"
ADDNEWLINE="Yes/No"
ATTRIBUTES="file_attributes">
56 CFML Language Reference
FILE
Required. The full path name of the file to be created.
OUTPUT
Required. The content of the file to be created.
MODE
Optional. Defines permissions for a file on Solaris or HP-UX. Ignored in Windows.
Valid entries correspond 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 the owner read/write permissions and group/other read permission.
MODE=666
Assigns read/write permissions for owner, group, and other.
MODE=777
Assigns read, write, and execute permissions for all.
ADDNEWLINE
Optional. Yes or No. If this attribute is set to Yes, a new line character is appended
to the text that is written to the file. If this attribute is set to No, no new line
character is appended to the text. The default value is Yes.
ATTRIBUTES
Optional. 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 as well as any other attributes, Normal is overridden by whatever other
attribute is specified.
Individual attributes must be specified explicitly. For example, if you specify just
the ReadOnly attribute, all other existing attributes are overwritten.
Chapter 1: ColdFusion Tags 57
Example The following example creates a file with the information a user entered into an HTML
insert form:
<CFFILE ACTION="Write"
FILE="c:\files\updates\#Form.UpdateTitle#.txt"
OUTPUT="Created By: #Form.FullName#
Date: #Form.Date#
#Form.Content#">
If the user submitted a form where:
UpdateTitle="FieldWork" FullName="World B. Frueh" Date="10/30/98" Content="We had a wonderful time in Cambridgeport."
ColdFusion would create a file named FieldWork.txt in the c:\files\updates\ directory and the file would contain the text:
Created By: World B. Frueh Date: 10/30/98 We had a wonderful time in Cambridgeport.
This following examples show the use of the MODE attribute for UNIX. The first, creates the file group/other=read).
<CFFILE ACTION="Write"
FILE="/tmp/foo"
MODE=644>
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?">
The next example uploads a file and gives it rwx-rw-rw permissions (owner/group/ other=read/write).
CFFILE ACTION="Upload"
FILEFIELD="fieldname"
DESTINATION="/tmp/program.exe"
MODE=755>
/tmp/foo with permissions defined as rw-r—r-- (owner=read/write,
58 CFML Language Reference
CFFILE ACTION="Append"
Use CFFILE with the Append action to append additional text to the end of an existing text file, for example, when creating log files.
Syntax <CFFILE ACTION="Append"
FILE="full_path_name"
OUTPUT="string"
ATTRIBUTES="file_attributes">
FILE
Required. The full path name of the file to which the content of the OUTPUT
attribute is appended.
OUTPUT
Required. The string to be appended to the file designated in the DESTINATION
attribute.
ADDNEWLINE
Optional. Yes or No. If this attribute is set to Yes, a new line character is appended
to the text that is written to the file. If this attribute is set to No, no new line
character is appended to the text. The default value is Yes.
ATTRIBUTES
Optional. A comma-delimited list of file attributes to be set on the file being
appended. 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 as well as any other attributes, Normal is overridden by whatever other
attribute is specified.
Individual attributes must be specified explicitly. For example, if you specify just
the ReadOnly attribute, all other existing attributes are overwritten.
Example The following example appends the text string "But Davis Square is the place to be. " to
the file
fieldwork.txt which was created in the previous example:
<CFFILE ACTION="Append"
FILE="c:\files\updates\fieldwork.txt"
OUTPUT="<B>But Davis Square is the place to be.</B>">
Chapter 1: ColdFusion Tags 59
CFFORM
CFFORM allows you to build a form with CFML custom control tags that provide much greater functionality than standard HTML form input elements.
Syntax <CFFORM NAME="name"
ACTION="form_action"
ENABLECAB="Yes/No"
ONSUBMIT="javascript"
TARGET="window_name"
ENCTYPE="type"
PASSTHROUGH="HTML_attributes">
... </CFFORM>
NAME
Optional. A name for the form you are creating.
ACTION
Required. The name of the ColdFusion page that will be executed when the form is
submitted for processing.
ENABLECAB
Optional. Yes or No. Allows users to download the Microsoft cabinet (*.cab) file(s)
containing the Java classes used for Java applet-based CFFORM controls. If Yes, on
opening the page, users are asked if they want to download the CAB file.
ONSUBMIT
Optional. JavaScript function to execute after other input validation returns. Use
this attribute to execute JavaScript for preprocessing data before the form is
submitted. See Developing Web Applications with ColdFusion for information on
using JavaScript for form validation.
TARGET
Optional. The name of the window or window frame where the form output will
be sent.
ENCTYPE
Optional. The MIME type used to encode data sent via the POST method. The
default value is application/x-www-form-urlencoded. It is recommended that you
accept the default value. This attribute is included for compatibility with the
HTML FORM tag.
PASSTHROUGH
Optional. HTML attributes that are not explicitly supported by CFFORM. If you
specify an attribute and its value, the attribute and value are passed to the HTML
60 CFML Language Reference
code that is generated for the CFINPUT tag. See the Usage section for more
information about specifying values.
Usage The following custom control tags are available:
CFINPUT — Creates a form input element (radio button, text box, or checkbox)
and can validate form input.
CFSELECT — Creates a drop down listbox.
CFSLIDER — Creates a slider control.
CFTEXTINPUT — Creates a text input box.
CFTREE — Creates a tree control.
CFGRID — Creates a grid control for displaying tabular data in a ColdFusion
form.
CFAPPLET — Embeds a registered Java applet in a ColdFusion form. Applets are
registered in the ColdFusion Administrator.
You can add standard and dynamic HTML FORM tag attributes and their values to the CFFORM tag by using the PASSTHROUGH attribute. These attributes and values are passed directly through ColdFusion to the browser in creating a form.
If you specify a value in quotation marks, you must escape the quotation marks by doubling them, for example,
PASSTHROUGH= "readonly= " "YES " " "
The ENABLECAB attribute is supported only for MS Internet Explorer clients that have Authenticode 2.0 installed. Authenticode 2.0 can be downloaded from http://
www.microsoft.com/ie/security/authent2.htm.
Note These CAB files are digitally signed using VeriSign digital IDs to ensure
file security.
Incorporating HTML form tags
CFFORM allows you to incorporate standard HTML in two ways:
You can add standard FORM tag attributes and their values to the CFFORM tag.
These attributes and values are passed directly through ColdFusion to the browser in creating a form. For example, you can use FORM tag attributes like TARGET to enhance your CFFORM features.
HTML tags that can ordinarily be placed within an HTML FORM tag can also be
placed between <CFFORM> and </CFFORM> tags.
For example, you use a standard HTML INPUT tag to create a submit button in a CFFORM:
<CFFORM
<INPUT TYPE="Submit" VALUE=" Update... "> </CFFORM>
Chapter 1: ColdFusion Tags 61
Example <!--- This example shows the use of CFINPUT controls in
a CFFORM ---> <HTML> <HEAD> <TITLE> CFFORM Example </TITLE> </HEAD>
<BODY> <H3>CFFORM Example</H3>
<CFIF IsDefined("form.oncethrough") is "Yes">
<CFIF IsDefined("form.testVal1") is True>
<H3>Results of Radio Button Test</H3>
<CFIF form.testVal1 is "Yes">Your radio button answer was yes</CFIF>
<CFIF form.testVal1 is "No">Your radio button answer was no</CFIF>
</CFIF>
<CFIF IsDefined("form.chkTest2") is True>
<H3>Results of Checkbox Test</H3>
Your checkbox answer was yes
<CFELSE>
<H3>Results of Checkbox Test</H3>
Your checkbox answer was no </CFIF> <CFIF IsDefined("form.textSample") is True AND form.textSample is not ""> <H3>Results of Credit Card Input</H3>
Your credit card number, <CFOUTPUT>#form.textSample#</CFOUTPUT>,
was valid under the MOD 10 algorithm. </CFIF> <CFIF IsDefined("form.sampleSlider") is "True"> <H3>You gave this page a rating of <CFOUTPUT>#form.sampleSlider#
</CFOUTPUT></H3>
</CFIF> <hr noshade>
</CFIF> <!--- begin by calling the cfform tag ---> <CFFORM ACTION="cfform.cfm" METHOD="POST" ENABLECAB="Yes">
<TABLE> <TR>
<TD> <H4>This example displays the radio button input type for CFINPUT.</H4> Yes <CFINPUT TYPE="Radio" NAME="TestVal1" VALUE="Yes" CHECKED="yes"> No <CFINPUT TYPE="Radio" NAME="TestVal1" VALUE="No"> </TD>
</TR>
<TR>
<TD> <H4>This example displays the checkbox input type for CFINPUT.</H4>
62 CFML Language Reference
<CFINPUT TYPE="Checkbox" NAME="ChkTest2" VALUE="Yes"> </TD>
</TR>
<TR>
<TD> <H4>This example shows a client-side validation for CFINPUT text boxes.</H4> <BR>(<I>This item is optional</I>)<BR> Please enter a credit card number: <CFINPUT TYPE="Text" NAME="TextSample" MESSAGE="Please enter a Credit
Card Number" VALIDATE="creditcard" REQUIRED="No">
</TD>
</TR>
<TR>
<TD> <H4>This example shows the use of the CFSLIDER tag.</H4> <P>Rate your approval of this example from 1 to 10 by sliding the
control.
<P>1 <CFSLIDER NAME="sampleSlider" LABEL="Sample Slider" RANGE="1,10"
MESSAGE="Please enter a value from 1 to 10" SCALE="1" BOLD="No" ITALIC="No" REFRESHLABEL="No"> 10
</TD>
</TR> </TABLE>
<P><INPUT TYPE="SUBMIT" NAME="SUBMIT" VALUE="show me the result"> <INPUT TYPE="Hidden" NAME="oncethrough" VALUE="yes"> </CFFORM>
</BODY> </HTML>
Chapter 1: ColdFusion Tags 63
CFFTP
CFFTP allows users to implement File Transfer Protocol operations. By default, CFFTP caches an open connection to an FTP server.
Note The CFFTP tag is for moving files between a ColdFusion server and an
FTP server. CFFTP cannot move files between a ColdFusion server and a
browser (client). Use CFFILE ACTION="UPLOAD" to transfer files from
the client to a ColdFusion server; use CFCONTENT to transfer files from a
ColdFusion server to the browser.
Note also that ColdFusion Server Basic security settings may prevent CFFTP from executing. These settings are managed using the ColdFusion Administrator Basic Security page. In order for CFFTP to execute, CFObject needs to be enabled on the Basic Security page. If you write ColdFusion applications designed to run on a server that is used by multiple customers, you need to consider the security of the files that the customer can move. Please refer to Administering ColdFusion Server for more information about securing ColdFusion tags.
CFFTP topics:
Establishing a Connection with CFFTP
File and Directory Operations with CFFTP
Accessing the Columns in a Query Object
CFFTP.ReturnValue Variable
Connection Caching
Establishing a Connection with CFFTP
Use this form of the CFFTP tag to establish a connection with an FTP server.
If you use connection caching to an already active FTP connection, you don’t need to respecify the connection attributes:
USERNAME
PAS SWORD
SERVER
Note Changes to a cached connection, such as changing RETRYCOUNT or
TIMEOUT values, may require reestablishing the connection.
Syntax <CFFTP ACTION="action"
USERNAME="name" PASSWORD="password" SERVER="server" TIMEOUT="timeout in seconds"
64 CFML Language Reference
PORT="port" CONNECTION="name" PROXYSERVER="proxyserver" PROXYBYPASS="proxybypass" RETRYCOUNT="number" STOPONERROR="Yes/No" PASSIVE="Yes/No">
ACTION
Required. Determines the FTP operation to perform. To create an FTP connection, use Open. To terminate an FTP connection, use Close. See Connection Caching for more information.
USERNAME
Required for Open. User name to pass in the FTP operation.
PASSWORD
Required for Open. Password to log the user.
SERVER
Required for Open. The FTP server to connect to, as in
ftp.myserver.com
TIMEOUT
Optional. Value in seconds for the timeout of all operations, including individual data request operations. Defaults to 30 seconds.
PORT
Optional. The remote port to connect to. Defaults to 21 for FTP.
CONNECTION
Optional. The name of the FTP connection. Used to cache the current FTP connection or to reuse connection information from a previous connection of the same name. All calls to CFFTP with the same connection name will reuse the same FTP connection information.
PROXYSERVER
Optional. A string that contains the name of the proxy server (or servers) to use if proxy access was specified. If this parameter is NULL, the tag reads proxy information from the registry.
PROXYBYPASS
Optional. An optional list of host names or IP addresses, or both, that are known locally. Requests to these names are not routed through the proxy. The list can contain wildcards, such as "157.55.* *int*", meaning any IP address starting with
157.55, or any name containing the substring "int", will bypass the proxy. If this parameter specifies the "<local>" macro as the only entry, the tag bypasses any host name that does not contain a period. For example, "www.microsoft.com" is routed to the proxy, whereas "internet" is not. If this parameter is NULL, the tag reads the bypass list from the registry.
Chapter 1: ColdFusion Tags 65
RETRYCOUNT
Optional. Number of retries until failure is reported. Default is one (1).
STOPONERROR
Optional. Yes or No. When Yes, halts all processing and displays an appropriate error. Default is Yes.
When No, three variables are populated:
CFFTP.Succeeded – Yes or No.
CFFTP.ErrorCode – Error number
CFFTP.ErrorText – Message text explaining error type
PASSIVE
Optional. Boolean indicating whether to enable passive mode. By default, passive mode is disabled.
Example <!--- This view-only example shows the use of CFFTP --->
<HTML> <HEAD> <TITLE>CFFTP Example</TITLE> </HEAD> <BODY>
<H3>CFFTP Example</H3> <P>CFFTP allows users to implement File Transfer Protocol operations. By default, CFFTP caches an open connection to an FTP server.
<P>CFFTP operations are usually of two types: <UL>
<LI>Establishing a connection <LI>Performing file and directory operations
</UL> <P>This view-only example opens and verifies a connection, lists the files in a directory, and closes the connection. <!--­<P>Open a connection
<CFFTP ACTION="open" USERNAME="anonymous" CONNECTION="My_query" PASSWORD="youremail@email.net" SERVER="ftp.tucows.com" STOPONERROR="Yes">
<P>Did it succeed? <CFOUTPUT>#CFFTP.Succeeded#</CFOUTPUT> <P>List the files in a directory: <CFFTP ACTION="LISTDIR" STOPONERROR="Yes" NAME="ListFiles" DIRECTORY="lib"
66 CFML Language Reference
CONNECTION="my_query"> <CFOUTPUT QUERY="ListFiles">
#name#<BR>
</CFOUTPUT>
<P>Close the connection: <CFFTP ACTION="close" CONNECTION="My_query" STOPONERROR="Yes"> <P>Did it succeed? <CFOUTPUT>#CFFTP.Succeeded#</CFOUTPUT>
--->
</BODY> </HTML>
File and Directory Operations with CFFTP
Use this form of the CFFTP tag to perform file and directory operations with CFFTP. If you use connection caching to an already active FTP connection, you don’t need to
respecify the connection attributes:
USERNAME
PAS SWORD
SERVER
Syntax <CFFTP
ACTION="action" USERNAME="name" PASSWORD="password" NAME="query_name" SERVER="server" ASCIIEXTENSIONLIST="extensions" TRANSFERMODE="mode" FAILIFEXISTS="Yes/No" DIRECTORY="directory name" LOCALFILE="filename" REMOTEFILE="filename" ITEM="directory or file" EXISTING="file or directory name" NEW="file or directory name" PROXYSERVER="proxyserver" PROXYBYPASS="proxybypass" PASSIVE="Yes/No">
ACTION
Required if connection is not already cached. If connection caching is used, the ACTION attribute is not required. Determines the FTP operation to perform. Can be one of the following:
ChangeDir
Chapter 1: ColdFusion Tags 67
CreateDir
ListDir
GetFile
PutFile
Rename
Remove
GetCurrentDir
GetCurrentURL
ExistsDir
ExistsFile
Exists
Note: Names of objects (files and directories) are case-sensitive; thus, using ListDir on "
test.log " will not find a file named "test.LOG. "
When ACTION="ListDir", the Attributes column returns either "Directory" or "Normal." Other platform-specific values, such as "Hidden" and "System" are no longer supported.
When ACTION="ListDir", a "Mode" column is returned. This column contains an octal string representation of UNIX permissions, for example, "777," when appropriate.
Note also that there is a CFFTP.ReturnValue variable that provides the return value for some of these actions. The actions for which this variable returns a value are as follows:
GetCurrentDir
GetCurrentURL
ExistsDir
ExistsFile
Exists
The section CFFTP.ReturnValu e Variable explains what is returned in this variable.
USERNAME
Required if the FTP connection is not already cached. If connection caching is used, the USERNAME attribute is not required. User name to pass in the FTP operation.
PASSWORD
Required if the FTP connection is not already cached. If connection caching is used, the PASSWORD attribute is not required. Password to log the user.
68 CFML Language Reference
NAME
Required for ACTION="ListDir". Specifies the query name to hold the directory listing. See Usage for more information.
SERVER
Required if the FTP connection is not already cached. If connection caching is used, the SERVER attribute is not required. The FTP server to connect to.
TIMEOUT
Optional. Value in seconds for the timeout of all operations, including individual data request operations. Defaults to 30 seconds.
PORT
Optional. The remote port to connect to. Defaults to 21 for FTP.
CONNECTION
Optional. The name of the FTP connection. Used to cache the current FTP connection or to reuse connection information from a previous connection of the same name. All calls to CFFTP with the same connection name will reuse the same FTP connection information.
ASCIIEXTENSIONLIST
Optional. A semicolon delimited list of file extensions that force ASCII transfer mode when TRANSFERMODE="Auto". Default extension list is:
txt;htm;html;cfm;cfml;shtm;shtml;css;asp;asa
TRANSFERMODE
Optional. The FTP transfer mode you want to use. Valid entries are ASCII, Binary, or Auto. Defaults to Auto.
FAILIFEXISTS
Optional. Yes or No. Defaults to Yes. Specifies whether a GetFile operation will fail if a local file of the same name already exists.
DIRECTORY
Required for ACTION=ChangeDir, CreateDir, ListDir, and ExistsDir. Specifies the directory on which to perform an operation.
LOCALFILE
Required for ACTION=GetFile, and PutFile. Specifies the name of the file on the local file system.
REMOTEFILE
Required for ACTION=GetFile, PutFile, and ExistsFile. Specifies the name of the
file on the FTP server’s file system.
Chapter 1: ColdFusion Tags 69
ITEM
Required for ACTION=Exists, and Remove. Specifies the object, file or directory, of these actions.
EXISTING
Required for ACTION=Rename. Specifies the current name of the file or directory on the remote server.
NEW
Required for ACTION=Rename. Specifies the new name of the file or directory on the remote server.
RETRYCOUNT
Optional. Number of retries until failure is reported. Default is one (1).
STOPONERROR
Optional. Yes or No. When Yes, halts all processing and displays an appropriate error. Default is No.
When No, three variables are populated:
CFFTP.Succeeded – Yes or No.
CFFTP.ErrorCode – Error number (See STOPONERROR variables, below)
CFFTP.ErrorText – Message text explaining error condition
PROXYSERVER
Optional. A string that contains the name of the proxy server (or servers) to use if proxy access was specified. If this parameter is NULL, the tag reads proxy information from the registry.
PROXYBYPASS
Optional. An optional list of host names or IP addresses, or both, that are known locally. Requests to these names are not routed through the proxy. The list can contain wildcards, such as "157.55.* *int*", meaning any IP address starting with
157.55, or any name containing the substring "int", will bypass the proxy. If this parameter specifies the "<local>" macro as the only entry, the tag bypasses any host name that does not contain a period. For example, "www.microsoft.com" is routed to the proxy, whereas "internet" is not. If this parameter is NULL, the tag reads the bypass list from the registry.
PASSIVE
Optional. Boolean indicating whether to enable passive mode. By default, passive mode is disabled.
70 CFML Language Reference
CFFTP.ReturnValue Variable
The value of the CFFTP.ReturnValue variable is determined by the results of the ACTION attribute used in CFFTP.
CFFTP.ReturnValue Variable
CFFTP Action Value of CFFTP.ReturnValue
GetCurrentDir String value containing the current directory
GetCurrentURL String value containing the current URL
ExistsDir Yes or No
ExistsFile Yes or No
Exists Yes or No
Accessing the Columns in a Query Object
When you use CFFTP with the ListDir action, you must also specify a value for the NAME attribute. The value of the NAME attribute is used to hold the results of the ListDir action in a query object. The query object consists of columns you can reference in the form:
queryname.columname[row]
Where queryname is the name of the query as specified in the NAME attribute and columnname is one of the columns returned in the query object as shown in the
following table. Row is the row number for each file/directory entry returned by the ListDir operation. A separate row is created for each entry.
CFFTP Query Object Columns
Column Description
Name Filename of the current element
Path File path (without drive designation) of the
current element
URL Complete URL for the current element (file or
directory)
Length Number indicating file size of the current element
LastModified Unformatted date/time value of the current
element
Chapter 1: ColdFusion Tags 71
CFFTP Query Object Columns (Continued)
Column Description
Attributes String indicating attributes of the current element
IsDirectory Boolean value indicating whether object is a file
or directory
Connection Caching
Once you’ve established a connection with CFFTP, you can reuse the connection to perform additional FTP operations. To do this, you use the CONNECTION attribute to define and name an FTP connection object that stores information about the connection. Any additional FTP operations that use the same CONNECTION name automatically make use of the information stored in the connection object. This facility helps save connection time and drastically improves file transfer operation performance.
If you need to keep the connection open throughout a session or longer, you can use a session or application variable as the connection name. However, if you do this, you must explicitly specify the full variable name with the Close action when you are finished. Note that keeping a connection open prevents others from using the FTP
server; therefore, you should close the connection as soon as possible.
Note Changes to a cached connection, such as changing RETRYCOUNT or
TIMEOUT values, may require reestablishing the connection.
Example The following example opens an FTP connection, retrieves a file listing, showing file or
directory name, path, URL, length, and modification date. Connection caching is used to maintain the link to the server, and automatic error checking is enabled.
<CFFTP CONNECTION=FTP
USERNAME="betauser" PASSWORD="monroe" SERVER="beta.company.com" ACTION="Open" STOPONERROR="Yes">
<CFFTP CONNECTION=FTP
ACTION="GetCurrentDir" STOPONERROR="Yes">
<CFOUTPUT>
FTP directory listing of #cfftp.returnvalue#.<P>
</CFOUTPUT>
<CFOUTPUT>Return is #cfftp.returnvalue#</CFOUTPUT><BR>
72 CFML Language Reference
<CFFTP CONNECTION="FTP"
ACTION="listdir" DIRECTORY="/*." NAME="q" STOPONERROR="Yes">
<HR>FTP Directory Listing:<P> <CFTABLE QUERY="q" HTMLTABLE>
<CFCOL HEADER="<B>Name</B>" TEXT="#name#"> <CFCOL HEADER="<B>Path</B>" TEXT="#path#"> <CFCOL HEADER="<B>URL</B>" TEXT="#url#"> <CFCOL HEADER="<B>Length</B>" TEXT="#length#"> <CFCOL HEADER="<B>LastModified</B>" TEXT="Date(Format#lastmodified#)"> <CFCOL HEADER="<B>IsDirectory</B>" TEXT="#isdirectory#">
</CFTABLE>
Chapter 1: ColdFusion Tags 73
CFGRID
Used inside CFFORM, CFGRID allows you to place a grid control in a ColdFusion form. A grid control is a table of data divided into rows and columns. CFGRID column data is specified with individual CFGRIDCOLUMN tags.
See also CFGRIDROW and CFGRIDUPDATE tags.
Syntax <CFGRID NAME="name"
HEIGHT="integer" WIDTH="integer" VSPACE="integer" HSPACE="integer" ALIGN="value" QUERY="query_name" INSERT="Yes/No" DELETE="Yes/No" SORT="Yes/No" FONT="column_font" FONTSIZE="size" ITALIC="Yes/No" BOLD="Yes/No" HREF="URL" HREFKEY="column_name" TARGET="URL_target" APPENDKEY="Yes/No" HIGHLIGHTHREF="Yes/No" ONVALIDATE="javascript_function" ONERROR="text" GRIDDATAALIGN="position" GRIDLINES="Yes/No" ROWHEIGHT="pixels" ROWHEADERS="Yes/No" ROWHEADERALIGN="position" ROWHEADERFONT="font_name" ROWHEADERFONTSIZE="size" ROWHEADERITALIC="Yes/No" ROWHEADERBOLD="Yes/No" ROWHEADERWIDTH="col_width" COLHEADERS="Yes/No" COLHEADERALIGN="position" COLHEADERFONT="font_name" COLHEADERFONTSIZE="size" COLHEADERITALIC="Yes/No" COLHEADERBOLD="Yes/No" BGCOLOR="color" SELECTCOLOR="color" SELECTMODE="mode" MAXROWS="number" NOTSUPPORTED="text" PICTUREBAR="Yes/No" INSERTBUTTON="text"
74 CFML Language Reference
DELETEBUTTON="text" SORTASCENDINGBUTTON="text" SORTDESCENDINGBUTTON="text">
</CFGRID>
NAME
Required. A name for the grid element.
HEIGHT
Optional. Height value of the grid control in pixels.
WIDTH
Optional. Width value of the grid control in pixels.
VSPACE
Optional. Vertical margin spacing above and below the grid control in pixels.
HSPACE
Optional. Horizontal margin spacing to the left and right of the grid control in pixels.
ALIGN
Optional. Alignment value. Valid entries are: Top, Left, Bottom, Baseline, Texttop, Absbottom, Middle, Absmiddle, Right.
QUERY
Optional. The name of the query associated with the grid control.
INSERT
Optional. Yes or No. Yes allows end users to insert new row data into the grid. Default is No.
DELETE
Optional. Yes or No. Yes allows end users to delete row data in the grid. Default is No.
SORT
Optional. Yes or No. When Yes sort buttons are added to the grid control. When clicked the sort buttons perform a simple text sort on the selected column. Default is No.
FONT
Optional. Font name to use for all column data in the grid control.
FONTSIZE
Optional. Font size for text in the grid control, measured in points.
Chapter 1: ColdFusion Tags 75
ITALIC
Optional. Yes or No. Yes presents all grid control text in italic. Default is No.
BOLD
Optional. Yes or No. Yes presents all grid control text in boldface. Default is No.
HREF
Optional. URL to associate with the grid item or a query column for a grid that is populated from a query. If HREF is a query column, then the HREF value that is displayed is populated by the query. If HREF is not recognized as a query column, it is assumed that the HREF text is an actual HTML HREF.
HREFKEY
Optional. The name of a valid query column when the grid uses a query. The column specified becomes the Key no matter what the select mode is for the grid.
TARGET
Optional. Target attribute for HREF URL.
APPENDKEY
Optional. Yes or No. When used with HREF, Yes passes the CFGRIDKEY variable along with the value of the selected tree item in the URL to the application page specified in the CFFORM ACTION attribute. Default is Yes.
HIGHLIGHTHREF
Optional. Yes highlights links associated with a CFGRID with an HREF attribute value. No disables highlight. Default is Yes.
ONVALIDATE
Optional. The name of a valid JavaScript function used to validate user input. The form object, input object, and input object value are passed to the specified routine, which should return True if validation succeeds and False otherwise.
ONERROR
Optional. The name of a valid JavaScript function you want to execute in the event of a failed validation.
GRIDDATAALIGN
Optional. Enter Left, Right, or Center to position data in the grid within a column. Default is Left.
GRIDLINES
Optional. Yes or No. Yes enables rules (lines) in the grid control, No suppresses row and column rules. Default is Yes.
ROWHEIGHT
Optional. Enter a numeric value for the number of pixels to determine the minimum row height for the grid control. Used with CFGRIDCOLUMN
76 CFML Language Reference
TYPE="Image", you can use ROWHEIGHT to define enough room for graphics you want to display in the row.
ROWHEADER
Optional. Yes or No. Yes displays row labels in the grid control. Defaults to Yes.
ROWHEADERALIGN
Optional. Enter Left, Right, or Center to position data within a row header. Default is Left.
ROWHEADERFONT
Optional. Font to use for the row label.
ROWHEADERFONTSIZE
Optional. Size font for row label text in the grid control, measured in points.
ROWHEADERITALIC
Optional. Yes or No. Yes presents row label text in italic. Default is No.
ROWHEADERBOLD
Optional. Yes or No. Yes presents row label text in boldface. Default is No.
ROWHEADERWIDTH
Optional. The width, in pixels, of the row header column.
COLHEADERS
Optional. Yes or No. Yes displays column headers in the grid control. Defaults to Ye s.
COLHEADERALIGN
Optional. Enter Left, Right, or Center to position data within a column header. Default is Left.
COLHEADERFONT
Optional. Font to use for the column header in the grid control.
COLHEADERFONTSIZE
Optional. Size font for column header text in the grid control, measured in points.
COLHEADERITALIC
Optional. Yes or No. Yes presents column header text in italic. Default is No.
COLHEADERBOLD
Optional. Yes or No. Yes presents column header text in boldface. Default is No.
BGCOLOR
Optional. Background color value for the grid control. Valid entries are: black, magenta, cyan, orange, darkgray, pink, gray, white, lightgray, yellow.
Loading...