Developing Cold Fusion Applications Tutorial

This document accompanies the CF pages that are labeled lesson1, etc. The application is a simple Human Resources application. Our final application will include CF pages for user input, processing input, and outputting results. Additionally, I have include files demonstrating login procedures, the application framework, and security. These files are not fully documented. Additional references are the Allaire Documentation available for free from their web-site or you can purchase a book on ColdFusion, the book written by Ben Forta generally considered the best.

Lesson 1 – Web Development Process of Static Pages
1. 2. 3. 4. 5. Add simple text to the page: My Name is Ron Use the toolbar to edit the Font for the text you typed above. Save the file as: name.cfm (a good habit is to explicitly type the .cfm) ftp the file to your directory on the server In the browser address box input the address of where you saved the file: 6. Go back to CF Studio. By right mouse click on a tag the edit window appears. For example, right click on the text you typed and you can change the font tag.

Lesson 2 – CFSET
1. 2. 3. 4. 5. 6. Open the file from lesson 1 and rename it for lesson 2 (use SAVE AS) Under the text type <CFSET MyAge = “32”> Add <BR> and then text My Age is Add <CFOUTPUT>#MyAge#</CFOUTPUT> Save the file and view it in the browser. Select view source from your browser window. Do you see the CF tags? Why not?

* CFSET is used to assign a local variable * CFOUTPUT is required to output any Cold Fusion variable to the page. * Notice that CFStudio color codes the different types of tags, variables, etc.

Lesson 3 – More about variables
1. Create a new CF page 2. create a local variable using CFSET for FirstName (remember to put “” around the value of the variable) 3. create a local variable called LastName

4. create a final variable that concatenates the first two variables
<CFSET FullName = FirstName & “ “ & LastName>


5. Add text, My Name is: 6. Add a cfoutput tag to output the variable FullName after the text 7. Save the file, ftp to server, and view in browser. 8. An alternative method is to put the text inside of the cfoutput tags

<CFOUTPUT>My Name is: #FullName#</CFOUTPUT>

9. Save the file, ftp to server, and view in browser. There should be no difference between having the text inside or outside of the CFOUTPUT tags.

Several different types of variables: • Local • Form • Session • CGI • Client • Cookie All CF Variables are typeless, you don’t need to specify integer, text, or other types. Variable scope is different for each variable type. For example, the local variable we created with <CFSET> is only scoped for that page, furthermore, the variable is only available after the CFSET line since the CF code is interpreted sequentially.

Two tags were demonstrated: <CFSET> to define and set the value of local variables <CFOUTPUT> to replace the variable with its value and output it to the HTML page. - you put all variables in between # signs to replace variable name with its value. - You can put text, HTML tags, and client variables in between CFOUTPUT tags. It ignores them except for the # signs. - CFOUTPUT is a very important tag.

Lesson 4 – Querying a Database
1. Create a new page 2. Use the CFQUERY tag to embrace SQL query to the database.

SELECT FirstName. The CFOUTPUT tag must be outside of the table row <TR> tag. Also. StartDate.) delimiter for the end of the SQL. Also. note the use of special formatting tags for Dates and Currency. In this lesson we learn how to use the CFOUTPUT tag with HTML table tags to output each row of the query as a row of the table. 1. The variable names to output are the column names from the query you wrote.FirstName#’ However. numbers do not use single quotes.display the query result set as a table with the appropriate headings ---> <TABLE WIDTH="95%"> <TR> . LastName FROM Employee WHERE EmployeeID = #EmployeeID# Lesson 5 – Formatting the data Tables are the easiest method for controlling the layout of HTML pages. Then for each instance of the query a single row will be outputted. Temporary FROM Employees </CFQUERY> <CFOUTPUT QUERY=”EmployeeList”> #FirstName# #LastName# #StartDate# #Salary# #Temporary# </CFOUTPUT> Summary The CFQUERY tag is used to enclose SQL queries that are sent to the Datasource specified. <!--.<CFQUERY NAME=”EmployeeList” DATASOURCE=”Hrdatabase”> SELECT FirstName. To output the results of the query you use the CFOUTPUT tags but include the query name as shown. About CFQUERY The SQL does not get a semicolon (. LastName. LastName FROM Employee WHERE FirstName = ‘#Form. Salary. In a properly setup Cold Fusion Development environment you can view the table structure through CF Studio which greatly aids you in writing the SQL. For example: SELECT FirstName. text must be in single quotes when used in the WHERE clause. All other rules for CFOUTPUT still apply.

To use forms you need two pages: The form page and the action page.cfm” and call the corresponding action page “InsertAction. The form page is used to collect the data. Forms must identify the action page the data will be sent to and the HTTP method to use. It is suggested that you include the words form and action in the file names. Lesson 6 – Form Page 1. The HTTP method is GET. This can be used to insert new records into a database (use the SQL Insert). on a form used to collect new employee information for inserting into the database call it “InsertForm. the scope of form variables is the action page. The data is saved into a form variable. memorizing the special formatting tags like DollarFormat(salary) is not realistic.</TR> <CFOUTPUT QUERY="EmployeeList"> <TR> <TD>#FirstName#</TD> <TD>#LastName#</TD> <TD>#DateFormat(StartDate)#</TD> <TD>#DollarFormat(Salary)#</TD> <TD>#Temporary#</TD> </TR> </CFOUTPUT> </TABLE> <TH <TH <TH <TH <TH ALIGN="LEFT">First Name</TH> ALIGN="LEFT">Last Name</TH> ALIGN="LEFT">Start Date</TH> ALIGN="LEFT">Salary</TH> ALIGN="LEFT">Temporary</TH> 2. Thus. on the action page you must use an IF statement to see if they were checked. to update existing records (SQL Update). Check boxes and radio buttons do not send data to the Action page if they are not selected.cfm" METHOD="POST"> . Forms Forms allow the user to input data. For Cold Fusion applications always use the POST method. The form variables are sent to the action page where they are processed. Except for full-time developers. to search the database on specific criteria (the user-specified criteria goes in the Where clause).cfm”. <FORM ACTION="ActionPage. Note. All Cold Fusion pages must use the method “POST”. For example. Learn how to utilize the help in order to find special formatting tags.

You should be familiar with all the controls (input devices) available for collecting data from the user.Department#<BR> Temporary Status: #Form. The IF statement is shown below. However.LastName#<BR> Department:#Form. To identify the variable as a form variable precede it with Form.Temporary#<BR> </CFOUTPUT> 2.LastName#<BR></CFOUTPUT> <CFELSE> Last Name Not Entered!<BR> </CFIF> We can also use the IF logic to see if the checkbox for temporary is selected. If yes.use conditional logic to determine if the temporary variable is defined (selected on the form page). The user must enter text into the box so we check if they leave the field blank by using an IF statement. In web applications this is a critical difference. Also. <CFSET Valid = True> . <!--. Lesson 6 – Action Page 1.use conditional logic to determine if user entered information in the last name text field ---> <CFIF Form. <!--. This is only a simple action page that shows what the user input. Lesson 7 – Action page with Conditional Logic to Check Input There are several methods to validate user input and to check for values in radio buttons and check boxes. This course does not cover basic HTML.Temporary") IS "YES"> Status: Temporary Employee <CFELSE> Status: Permanent Employee </CFIF> An alternative approach to check the form input is with the Len tag. JavaScript is probably preferable for developing scalable web applications because it is performed on the client-side whereas Cold Fusion is performed on the server-side. display temporary. Here we will show the Cold Fusion approach. <CFOUTPUT> Last Name: #Form. you can define two local variables Valid and Error.LastName IS NOT ""> Last Name: <CFOUTPUT>#Form. Notice how we use this to specify whether the employee is temporary or permanent.3. else. Then at the end just check if Not Valid. display permanent status ---> <CFIF IsDefined("Form.

Email.At+1)> </CFIF> <CFIF (Len(Form.Email)> <CFIF At greater than 0> <CFSET At2 = Find("@".Check if a name has been provided ---> <CFIF Len(Form.Name) is 0> <CFSET Valid = False> <CFSET Error = Error & “A Name is required.Form.Form.". Cold Fusion provides a method to dynamically populate the select box options. This is a more complicated form validation since we cannot simple check if it is text or integer.<CFSET Error = “”> <!--.At+1)> <CFSET Dot = Find(". <!--.Check if the e-mail address is valid ---> <CFSET Dot = 0> <CFSET At2 = 0> <CFSET At = Find("@".Form. if the select box is for states then all 50 states must be programmed into the HTML page.Email) is not 0) and (At is 0 or At2 greater than 0 or Dot is 0)> <CFSET Valid = False> <CFSET Error = Error & “The E-mail Address is invalid. if we wish to add Puerto Rico as a new state then we just add it once to the database and it will appear dynamically on all select boxes.<BR>”> </CFIF> Here we check if the email entered is valid or not.dynamically populate drop down select box to allow users to search by department ---> <P> Department<BR> <SELECT NAME="Department_Name"> <OPTION VALUE="All">All</OPTION> <CFOUTPUT QUERY="GetDepartments"> <OPTION VALUE="#Department_Name#"> #Department_Name# </OPTION> </CFOUTPUT> </SELECT> CFINCLUDE . For example. <!--. So for example.<BR>”> </CFIF> Lesson 8 – dynamically populate drop-down boxes In most web applications when a drop-down select box is used the developer must enumerate all of the options.Email.

LastName LIKE '%#Form.Department_ID <!--.Use CFInclude to include code segments from other files. On the page you insert into you put the following code segment: <!--.LastName") IS "YES"> <CFIF Form.Department_Name.FirstName. this code allows the user to search on any single field or combination of all three fields. <!--. Departments WHERE Departments. Employees.LastName IS NOT ""> AND Employees.Temporary#' </CFIF> </CFQUERY> .LastName.StartDate.Department_Name#' </CFIF> </CFIF> <!--.LastName#%' </CFIF> </CFIF> <!--. For example to include the title bar.Department_Name IS NOT "ALL"> AND Departments.Temporary = '#Form. Employees.Temporary FROM Employees.use conditional logic to determine if the temporary variable is defined (selected on the form page) ---> <CFIF IsDefined("Form.Department_ID = Employees. Employees.include toolbar.use conditional logic to determine if user entered information in the last name text field ---> <CFIF IsDefined("Form.Salary.cfm---> <cfinclude template=" dynamic query to get employee information based on user search criteria ---> <CFQUERY NAME="EmployeeSearch" DATASOURCE="HRSolution"> SELECT Employees.Department_Name") IS "YES"> <CFIF Form.Temporary") IS "YES"> AND Employees. If the user does not enter a last name then it is not used in the query. Lesson 8 – Action page that dynamically generates SQL In order to search on multiple items but also allow the user to only input a subset of them you use conditional logic embedded into the SQL.use conditional logic to determine if the user would like to search on all departments or just an individual department ---> <CFIF IsDefined("Form.cfm"> The code you insert should not have the <HTML> AND </HTML> tags since it will be inserted into another page.Department_Name = '#Form. Departments. For example. Employees.

Notice how we use the form variables in the Values section.FirstName#'.insert a new employee record into the employee table ---> <CFQUERY NAME="InsertEmployee" DATASOURCE="HRSolution"> INSERT INTO Employees (FirstName. <br> Please click the back button and try again. <b>Employee First Name</b><BR> <INPUT TYPE="Text" NAME="FirstName" size="20" maxlength="50"> To enforce a date format use VariableName_Date or to enforce a real number use VariableName_float.check to determine if any records have been returned based on the users search criteria ---> <CFIF EmployeeSearch. Instead of letting the system generate an error you add the following code that utilizes a property of the query called RecordCount. Department_ID. StartDate.'#Form. a valid date and numeric value for the salary field ---> <INPUT TYPE="HIDDEN" NAME="FirstName_Required" VALUE="First Name is Required!"> Here is the corresponding input text box. Temporary) VALUES ('#Form. The message the user is prompted goes into the Value. Lesson 9 – Action page to insert values We simple use SQL and the Insert command to insert the user entered data into the database.RecordCount IS "0"> No records match your search criteria. <!--. <!--. Salary. '#TempStatus#') </CFQUERY> . LastName. #Form.LastName#'.Department_ID#.#Form. <!--. Lesson 9 – Using Hidden Fields in forms to validate input The name of the hidden field must be the Input Name with an underscore (“_”) Required.Salary#. #Form.Sometimes there may be no records in the database that must the user’s search.perform server side validation to ensure the user entered a last name.StartDate#.

6.cfm template is ever found then processing of the requested *. Accessible by all clients and applications in a single server.cfm page is processed. 2.cfm template is found then it is processed first.cfm template. Consequently.cfm template requested is processed. seconds)#” . client.cfm template. The process of a user request for a page is as follows: 1. 3.cfm template is requested in the application. before all other *. Exists for a single client in a single session For an application and accessible by multiple clients.cfm template is found it checks the next higher directory. ColdFusion checks the directory for an application. and then the *. 5. hours. To enable session.Application Framework An application is a set of ColdFusion Templates that enables you to: • Maintain state by setting variables that can be accessed from any template in the application (scope is the entire application). After the *.cfm template is consequently processed everytime a *.cfm templates in the application. you could define global variables and procedures in the application.cfm template is requested ColdFusion then searches for a OnRequestEnd.cfm template takes place as usual. minutes.cfm template is processed first. The application. User requests a cfm page in the application. If no application. If the application. These variables are: Variable Type Client Session Application Server Description Tied to a single client (or browser) and can persist over multiple sessions. The application. If found this template is then processed. and application management you use the following tag: <CFAPPLICATION NAME=”MyAppName” CLIENTMANAGEMENT = “Yes/No” SESSIONMANAGEMENT = “Yes/No” SETCLIENTCOOKIES = “Yes/No” SESSIONTIMEOUT= “#CreateTimeSpan(days. Before the *. 4. • Provide custom error messages • Enhance the security of an application The application framework consists of an application.cfm template that must be saved in the root directory and variables that have scope throughout the entire application. If no application.cfm template that will be processed each time.

Two client variables are set by default: CFID An CFTOKEN incremental ID for each client that connects to the server A random number used in conjunction with CFID to uniquely identify a particular client.CLIENTSTORAGE = “registry or cookie or name of datasource” SetDomainCookies = “Yes/No” > Attribute NAME SESSIONMANAGEMENT SESSIONTIMEOUT CLIENTMANAGEMENT CLIENTSTORAGE SETCLIENTCOOKIES Description Name of the application Enables session variables Time limit after which session expires (don’t make too long) Enables client variables Specifies where to store client variables Specifies whether you use cookies when defining session and client variables (otherwise you must pass it on the URL) Value Name Yes/No Use the createtimesp an function. show sports stories. You use these for: • • • • • User display preferences such as background colors User content preferences such as stocks to watch. Yes/no Registry or cookie or data source Yes/No Default No Required Yes No No Registry Yes No No No Client Management Client variables are for a single client and persist over multiple sessions. Counts of how many times a user visits and when they visit last Items in a shopping cart and past purchases Scores for quizzes or games Default Client Variables LastVisit the date and time of the last visit. etc. HitCount the number of hits on the application TimeCreated when the client cookie was first created .

Storage Alternatives The three storage options are registry. UserID and Password.SessionID. The LoginAction checks via query .cfm and Main. Lesson 10 Sophisticated Login Pages The database should have a table with two attributes. The cookies have limitations since clients may turn them off. application and server are not discussed here due to infrequent use. Session variables are intended to be used for a short period of time.cfm. You can use this to identify a single session and user. Using a datasource eliminates these problems but it increases the number of database calls from the application server. What CFLOCK does is it prevents others from use the shared resource until the first user releases it. Session Management Session variables are stored in the Server’s RAM (not very scalable). The LoginForm is used to input username and password. you can store more complex and larger variable data in session variables than client variables. The registry has limited memory and in a multi-server clustered environment cannot be used.user_name = “#form. Notice. A default session variable created is session. The system login requires three pages: LoginForm. cookies. You use session variables for: • • • • Enforcing user login Storing arrays instead of passing them between templates Storing calculations Storing query recordsets. Client variables are limited to 255 characters and no arrays or query recordsets.user_name#”> </CFLOCK> The CFLOCK tag is used to prevent problems with simultaneous read/write to shared variables.cfm LoginAction. To create a session variable: <CFLOCK TIMEOUT = “30” NAME=”#Session. a session variable is not shared it is recommended to use the CFLOCK. Although. The other two variable types. or external data sources.SessionID#”> <CFSET session.

user_name and form.cfm"> <FONT FACE="#face#" SIZE="2"> Your User ID and Password are not in our database.password = '#form.user_id = '#form. --------------------------------------------------------> <CFQUERY NAME="security_check" DATASOURCE="#db#"> SELECT passwords.password.cfm <FORM ACTION="LoginAction. --------------------------------------------------------> <CFIF SECURITY_CHECK.cfm" METHOD="POST"> <P>Please enter your user ID:<BR> <INPUT TYPE="Text" NAME="user_id" SIZE="20"> <P>Please enter your Password:<BR> <INPUT TYPE="password" NAME="password" SIZE="20"> <P> <INPUT TYPE="Submit" NAME="Submit" VALUE="Login"> </FORM> LoginAction.user_name FROM passwords WHERE passwords. If they do not match the user is prompted to try again.password are not valid then Prompt the user to log in again.password#' </CFQUERY> <!------------------------------------------------------If form.user_id.the database to see if they match. If they match the user is sent to the Main.cfm <!------------------------------------------------------Security_check query verifies that form. passwords. passwords.<BR>Please try again.cfm page via a CFLOCATION tag.user_id#' AND passwords. LoginForm. .user_name and form.password are valid.RECORDCOUNT IS 0> <CFOUTPUT> <HTML> <HEAD> <TITLE>#title#</TITLE> </HEAD> <BODY BGCOLOR="#bgcolor#"> <DIV ALIGN="center"> <CFINCLUDE TEMPLATE="login.

The CFERROR tag is best placed within the application.cfm” MAILTO=Ronald@eng. misspelled variable name or similar a “goto” statement that sends the user to the page (URL) listed. To define custom error handling you use: <CFERROR TYPE=”REQUEST” TEMPLATE=”error_request.cfm.cfm template --------------------------------------------------------> <CFELSE> <CFLOCK TIMEOUT="30" THROWONTIMEOUT="Yes" NAME="#Session. Request Errors: Occur due to misplaced template in an include tag.cfm template.STARTED = TRUE> </CFLOCK> <CFSET CLIENT.user_name is set.fiu.cfm" ADDTOKEN="no"> </CFIF> <CFABORT> .</FONT> </DIV> </BODY> </HTML> </CFOUTPUT> <CFABORT> <!------------------------------------------------------If the user_name and password are verified. .Stops processing of page.SessionID#" TYPE="Exclusive"> <CFSET SESSION.> And you must create of course the page error_request. Validation Errors: Occur when a user improperly completes and submits a form. such as not filling in a text box.user_name#"> <CFLOCATION URL="home. Error Handling You can define generalized error handling for your application. then the session is started.USER_NAME = "#security_check. and the user is redirected to the home. <CFLOCATION> .

4. For example. Trouble Shooting Trouble shooting skills require you to apply logic and the process of elimination. No closing tag For example. Common Errors: 1. type mismatch with databases Text requires single quotes and numbers do not. Also. 2.There are default error variable names such as error. forms.cfm) but you called the form to insert new employee records (EmployeeInsertForm.UserID and you forget the closing # sign. Spelling Mistakes Spelling of the code as well as the variables. . The reader is referred to ColdFusion user manual for the list of these variables. #Form. 3. This is inconsistent naming and will become difficult to manage.diagnostics which you can use. Mis-matching names Naming conventions are crucial. did you call a page to update employee records (UpdateEmployeeForm. need to validate form input to see that it matches the database table format. As sites become more complex if you haphazardly name variables.cfm). and pages then you will have difficulty managing your site.

The HR Database .

The Department Table .

The Employee Table .

and client variables for testing purposes. session. 0)#" APPLICATIONTIMEOUT="#CreateTimeSpan(2. allow cookies.cfm ---> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4. session timeout after 20 minutes. session variables on. Application timeout after 2 days. --------------------------------------------------------> <!--<CFSET STRUCTCLEAR(APPLICATION)> <CFSET STRUCTCLEAR(SESSION)> <CFLOOP INDEX="x" LIST="#GetClientVariablesList()#"> <CFSET DELETED = DELETECLIENTVARIABLE("#x#")> </CFLOOP> <CFCOOKIE NAME="cfid" EXPIRES="NOW"> <CFCOOKIE NAME="cftoken" EXPIRES="NOW"> <CFCOOKIE NAME="cfglobals" EXPIRES="NOW"> <CFABORT> ---> <!------------------------------------------------------Set Server constants that can be accessed by any client --------------------------------------------------------> <CFLOCK TIMEOUT="30" THROWONTIMEOUT="Yes" NAME="server" TYPE="Exclusive"> <CFIF NOT #ISDEFINED("server. 0.Application. and then replace the comments so the application will run normally.<!--. -------------------------------------------------> <CFSET SERVER.season")#> <!-----------------------------------------------The season is currently set to a string. You must remove the comments surrounding the next set of code variables to clear all variable scopes. client variables on. 0.0 Transitional//EN"> <!------------------------------------------------------Set application name. 0. store client variables in registry --------------------------------------------------------> <CFAPPLICATION NAME="MyApp" SESSIONMANAGEMENT="Yes" SETCLIENTCOOKIES="Yes" SESSIONTIMEOUT="#CreateTimeSpan(0.SEASON = "Spring Time"> </CFIF> </CFLOCK> <!------------------------------------------------------Set Application constants --------------------------------------------------------> . 20. 0)#" CLIENTMANAGEMENT="Yes" CLIENTSTORAGE="Registry"> <!------------------------------------------------------Used to reset application. but could easily be determined automatically by time of year.

CF_TEMPLATE_PATH IS NOT "#path#login.Started")> <CFSET LOGIN = ""> </CFIF> </CFLOCK> <CFIF ISDEFINED("Login")> <!---------------------------------------------------Since the session.cfm template).FACE = "Arial"> <CFSET APPLICATION.cfm and login2.EMAIL = "kmotlagh@geocities.TITLE = "My Quiz Application"> <CFSET APPLICATION. --------------------------------------------------------> <CFLOCK TIMEOUT="30" THROWONTIMEOUT="Yes" NAME="#Session.DB = "quiz"> <CFSET APPLICATION.Started")#> <CFSET APPLICATION.CF_TEMPLATE_PATH IS NOT "#path#login2.cfm")> <CFINCLUDE TEMPLATE="login.CF_TEMPLATE_PATH#)> <CFIF (CGI.cfm would be aborted unless the following cfif statement is added -----------------------------------------------------> <CFSET PATH=GETDIRECTORYFROMPATH(#CGI.cfm"> <!-----------------------------------------------Aborts processing of any template except"> <CFSET APPLICATION.ApplicationName#" TYPE="Exclusive"> <CFIF NOT #ISDEFINED("Application.BGCOLOR = "##ffffff"> <CFSET APPLICATION. If they haven't a non-persistent login variable is set. This is so you do not have to use a <CFLOCK> tag around the next block of code.cfm until user has logged in -------------------------------------------------> <CFABORT> </CFIF> </CFIF> .<CFLOCK TIMEOUT="30" THROWONTIMEOUT="Yes" NAME="#Application.started variable has not yet been set (it is set when the user successfully logs in in the login2. the processing of the login2.SessionID#" TYPE="ReadOnly"> <CFIF NOT ISDEFINED("Session.cfm") AND (CGI.STARTED = TRUE> </CFIF> </CFLOCK> <!------------------------------------------------------Test to see if user has logged in.

Check if a name has been provided ---> <CFIF Len(Form.<BR>”> </CFIF> <!--.<BR>”> </CFIF> <!--.Phone) is not 0) and (not IsNumeric(Replace(Form.At+1)> <CFSET Dot = Find(".Check if a phone number has been provided ---> <CFIF Len(Form.cfm”> <TABLE BORDER=0 CELLPADDING=5> <TR> <TD>Name</TD> <TD><INPUT TYPE=TEXT NAME=”Name” SIZE=30 MAXLENGTH=50></TD> </TR> <TR> <TD>Phone</TD> <TD><INPUT TYPE=TEXT NAME=”Phone” SIZE=8 MAXLENGTH=8></TD> </TR> <TR> <TD>E-mail</TD> <TD><INPUT TYPE=TEXT NAME=”Email” SIZE=20 MAXLENGTH=30></TD> </TR> <TR> .”-“.<BR>”> </CFIF> <!--.Email) is not 0) and (At is 0 or At2 greater than 0 or Dot is 0)> <CFSET Valid = False> <CFSET Error = Error & “The E-mail Address is invalid.Phone) is 0> <CFSET Valid = False> <CFSET Error = Error & “A Phone Number is required.””)) is not 7)> <CFSET Valid = False> <CFSET Error = Error & “The Phone Number is invalid.Email)> <CFIF At greater than 0> <CFSET At2 = Find("@".Phone.Form.Check if the e-mail address is valid ---> <CFSET Dot = 0> <CFSET At2 = 0> <CFSET At = Find("@".Form.Phone.Check if the phone number is valid ---> <CFIF (Len(Form.</STRONG><HR> <CFOUTPUT>#Error#</CFOUTPUT> <EM>Please correct the error</EM> <FORM METHOD=”POST” ACTION=”submit.Check if the form is valid or not ---> <CFIF not Valid> <STRONG>Sorry.At+1)> </CFIF> <CFIF (Len(Form.Email.Form.Name) is 0> <CFSET Valid = False> <CFSET Error = Error & “A Name is required.<CFSET Valid = True> <CFSET Error = “”> <!--.". An error occurred.<BR>”> </CFIF> <!--.”-“.Email.””)) or Len(Replace(Form.

<TD></TD> <TD><INPUT TYPE=SUBMIT></TD> </TR> </TABLE> </FORM> <CFELSE> <!--.Place normal form-processing code here ---> <H1>The Form is Valid!</H1> </CFIF> .

to# has been sent </P> </CFOUTPUT> <CFELSE> <H1>Oops …</H1> <P>You need to provide an E-mail address for the recipient. computer-generated greeting sent to You courtesy of and the CFMAIL tag. Hit the Back button to return to the form and provide" FROM="address@some. </CFMAIL> <H1>Message Sent</H1> <CFOUTPUT> <P>Your message to is not ""> <CFMAIL TO="#Form.</P> </CFIF> </BODY> </HTML> ." SUBJECT="A Greeting"> Hi! This is a quick.<HTML> <HEAD> <TITLE>Sending Your Greeting</TITLE> </HEAD> <BODY> <CFIF Form.

’mm/dd/yy’)#" ENDTIME="" INTERVAL="Daily"> <H1>Job Scheduled</H1> <HR> <CFOUTPUT> The report #Form.cfm" FILE="" OPERATION="HTTPRequest" URL="http://cold.username#-#Form.<HTML> <HEAD> <TITLE>Job Scheduled</TITLE> </HEAD> <BODY> <CFSCHEDULE ACTION="Update" TASK="#Form.server/reports/#Form.’mm/dd/yy’)#" STARTTIME="23:00" ENDDATE="#dateformat(now(). for #Form.html">here</A> to schedule another </CFOUTPUT> <P> Click <A HREF="form. </BODY> </HTML> has been scheduled to run tonight at 11:00" PATH="\\homedirserver\#Form.username#\" PUBLISH="Yes" STARTDATE="#dateformat(now().

or UserObject. This is done through the ColdFusion Administration Page. 2. It can be: Application. IsAuthorized (“ResourceType”. You would use the CFAuthenticate tag in the application. Associate User Directory with a Security Context. This is done through the ColdFusion Administration Page. Collection. Define a security context. To establish security you must: 1. “Action”) Resource type must match a resource in the security context definition. Tags CFAUTHENTICATE checks a username and password combination against a given security context. Obviously. Specify a user directory to contain a list of users and groups of users to specify permissions to specific resources. Component. This is done through the ColdFusion Administration Page. This is done through the ColdFusion Administration Page. Specify a secure server (the ColdFusion Server in our case). . <CFAUTHENTICATE SECURITYCONTEXT=”HumanResourceSalary” USERNAME=”User name goes here” PASSWORD=”Password goes here”> The IsAuthenticated function is used to check if a user is authenticated. These tags work with a directory of usernames and passwords for authentication and authorization to access certain resources.Security ColdFusion provides three tags for enforcing security of an application. The function returns either True or False. 6. 4. Rules define what actions are available on which resources. you can use the IsAuthenticated and IsAuthorized tags to obtain results. 5. “ResourceName”. Define Security Rules. CustomTag.cfm page use the appropriate tags to authenticate users. In the Application. 7. you could use IsAuthenticated to advantage with a CFIF tag. A security context defines a cohesive group of resources and their security information.cfm page since this page is accessed before all templates. CFML. Create a Security Policy that defines what user(s) are covered by what policies. 3. This is done through the ColdFusion Administration Page. The IsAuthorized tag is used to secure specific resources based on the access policies created in the security context. File. Once checked.

IF WE HAVE A PASSWORD AND USERNAME.Password")> <CFSET PASSWORD=Form.CHECK AUTHENTICATION STATUS AND IF NOT AUTHENTICATED HANDLE IT ---> <CFIF NOT IsAuthenticated()> <!--.Username#"> <CFELSE> <CFSET HaveUsername = "No"> </CFIF> </CFIF> <!--.Password")> <CFSET PASSWORD=Cookie.Password> <CFCOOKIE NAME="password" VALUE="#Form.Username> <CFCOOKIE NAME="username" VALUE="#Form.Password#"> <CFELSE> <CFSET HavePassword = "No"> </CFIF> </CFIF> <!--. Example Application.Password> <CFELSE> <CFSET PASSWORD=""> <CFIF IsDefined("Form. TRY AUTHENTICATING ---> <CFIF HaveUsername and HavePassword> <CFTRY> <CFAUTHENTICATE SECURITYCONTEXT="EmployeeList" USERNAME="#USERNAME#" PASSWORD="#PASSWORD#" SETCOOKIE="Yes"> <!--. For example.Username> <CFELSE> <CFSET USERNAME=""> <CFIF IsDefined("Form.Username")> <CFSET USERNAME=Form.Username")> <CFSET USERNAME=Cookie.IF AN EXCEPTION IS THROWN.Actions depend on the resource type since not every action is possible with every resource. HANDLE IT ---> <CFCATCH TYPE="Security"> <CFCOOKIE NAME="username" VALUE="" EXPIRES="NOW"> <CFCOOKIE NAME="password" VALUE="" EXPIRES="NOW"> <CFLOCATION URL="index. for a File actions can be Read or Write.cfm"> </CFCATCH> .cfm listing <!--.CHECK FOR A PASSWORD ---> <CFPARAM name=”HavePassword” default=”Yes”> <CFIF IsDefined("Cookie.CHECK FOR A USERNAME ---> <CFPARAM name=”HaveUsername” default=”Yes”> <CFIF IsDefined("Cookie. You are referred to the CF manual for further details.

USER IS AUTHENTICATED.</CFTRY> </CFIF> <!--.OUTPUT A LOGIN FORM ---> <FORM ACTION="index.cfm" METHOD="POST"> Username: <INPUT TYPE=text NAME="username"><BR> Password: <INPUT TYPE=password NAME="password"><BR> <INPUT TYPE=submit VALUE="LOGIN"> </FORM> <CFABORT> </CFIF> <!--. SO WE CONTINUE ---> <CFAPPLICATION NAME="admin"> .

cfm”> <TABLE BORDER=0 CELLPADDING=5> <TR> <TD>Name</TD> <TD><INPUT TYPE=TEXT NAME=”Name” SIZE=30 MAXLENGTH=50></TD> </TR> <TR> <TD>Phone</TD> <TD><INPUT TYPE=TEXT NAME=”Phone” SIZE=8 MAXLENGTH=8></TD> </TR> <TR> <TD>E-mail</TD> <TD><INPUT TYPE=TEXT NAME=”Email” SIZE=20 MAXLENGTH=30></TD> </TR> <TR> .Email) is not 0) and (At is 0 or At2 greater than 0 or Dot is 0)> <CFSET Valid = False> <CFSET Error = Error & “The E-mail Address is invalid. An error occurred.Email.””)) is not 7)> <CFSET Valid = False> <CFSET Error = Error & “The Phone Number is invalid.Name) is 0> <CFSET Valid = False> <CFSET Error = Error & “A Name is required.”-“.””)) or Len(Replace(Form.Phone) is not 0) and (not IsNumeric(Replace(Form.At+1)> <CFSET Dot = Find(".Check if the form is valid or not ---> <CFIF not Valid> <STRONG>Sorry.”-“.Phone) is 0> <CFSET Valid = False> <CFSET Error = Error & “A Phone Number is required.Form.</STRONG><HR> <CFOUTPUT>#Error#</CFOUTPUT> <EM>Please correct the error</EM> <FORM METHOD=”POST” ACTION=”submit.".Phone.At+1)> </CFIF> <CFIF (Len(Form.Form.<BR>”> </CFIF> <!--.Check if the e-mail address is valid ---> <CFSET Dot = 0> <CFSET At2 = 0> <CFSET At = Find("@".Check if the phone number is valid ---> <CFIF (Len(Form.Email)> <CFIF At greater than 0> <CFSET At2 = Find("@".Check if a phone number has been provided ---> <CFIF Len(Form.Check if a name has been provided ---> <CFIF Len(Form.Form.Email.<BR>”> </CFIF> <!--.<BR>”> </CFIF> <!--.<BR>”> </CFIF> <!--.<CFSET Valid = True> <CFSET Error = “”> <!--.Phone.

<TD></TD> <TD><INPUT TYPE=SUBMIT></TD> </TR> </TABLE> </FORM> <CFELSE> <!--.Place normal form-processing code here ---> <H1>The Form is Valid!</H1> </CFIF> .

Sign up to vote on this title
UsefulNot useful