YOUR FEEDBACK
José D'Andrade wrote: "...it may never be released..." Why? "...if Midori isn’t heir to Windows Mi...
AJAXWorld RIA Conference
$300 Savings Expire August 8
Register Today and SAVE!


2007 West
GOLD SPONSORS:
Active Endpoints
Your SOA Needs BPEL for Orchestration
BEA
Virtualized SOA: Adaptive Infrastructure for Demanding Applications
Nexaweb
Overcoming Bandwidth Challenges with Nexaweb
TIBCO
What is Service Virtualization?
SILVER SPONSORS:
WSO2
Using Web Services Technologies and FOSS Solutions
Click For 2007 East
Event Webcasts

2008 East
PLATINUM SPONSORS:
Appcelerator
Think Fast: Accelerate AJAX Development with Appcelerator
GOLD SPONSORS:
DreamFace Interactive
The Ultimate Framework for Creating Personalized Web 2.0 Mashups
ICEsoft
AJAX and Social Computing for the Enterprise
Kaazing
Enterprise Comet: Real–Time, Real–Time, or Real–Time Web 2.0?
Nexaweb
Now Playing: Desktop Apps in the Browser!
Sun
jMaki as an AJAX Mashup Framework
POWER PANELS:
The Business Value
of RIAs
What Lies Beyond AJAX?
KEYNOTES:
Douglas Crockford
Can We Fix the Web?
Anthony Franco
2008: The Year of the RIA
Click For 2007 Event Webcasts
SYS-CON.TV
TOP COLDFUSION LINKS


Creating Variables in CFML
The basis of many CF programming projects

Welcome to CF101, a new column I'll be writing for ColdFusion Developer's Journal. This column is dedicated to all of you beginners out there, to teach you the basics of ColdFusion development. You don't need to have a prior understanding of programming, HTML, or Web development to read this column, although if you do, it's a great way to help reinforce the basics.

For the first column, I thought I'd talk a bit about what variables are and how we can create and use them in ColdFusion. Before we jump into that, I thought you might like to know a little bit about my development experience.

Who is Jeffry Houser?
My experience in the IT world started over seven years ago. I was the "tech guy" at a small advertising firm. I did a bit of everything, but most of the development was in Lotus Notes. I worked with very early versions of the Lotus Domino Web Server. Back then, building Web sites in Domino was like trying to tie your shoes while wearing two pairs of gloves and some mittens. It was possible, just not very easy.

Around 4:59 one Friday evening, I was handed a project with a Monday morning deadline. Another developer had left the company for greener pastures and one of his projects had been left unfinished. The project was being built in ColdFusion with Microsoft Access in the database. Although I had no previous ColdFusion training, I was able to complete the project in 10 hours on a rainy Saturday. I haven't looked backed since.

I left that small advertising firm in 1999 to start DotComIt, a Web consulting company. Since starting DotComIt, I've written three ColdFusion books, including ColdFusion: A Beginner's Guide; spoken at a bunch of user groups; and written a handful of articles. I've dealt with a lot of technologies over the years, but ColdFusion remains my favorite Web development technology because of its simplicity. I've always had a knack for describing the complex in a straightforward way, and that is why the folks at CFDJ thought of me when they decided to create this column. I have also been a musician for over 20 years and own a recording studio. I mention that only because many people find it more interesting than my Web development adventures. Hopefully my life story doesn't stick in your head for too long; let's talk about variables.

Understanding What a Variable Is
Before I explain how to use variables within CFML (CFML is the programming language of ColdFusion and BlueDragon; whereas ColdFusion specifically refers to the Macromedia server product), I want to make sure that you understand what variables are. A variable in programming is very similar to a variable in algebra. It has two parts: a name and a value. You can use the variable's name to refer to the variable's value. In computing, the variable is a place in memory where a value is stored. You can assign a name to the place in memory to reference its value.

You might want to ask why we would want to use a variable instead of just using the value that it points to. That would be a good question; and there are multiple reasons. First, a variable's value can change, but the variable name never does. If we use the variable in 100 spots, then we only have to change it once, not 100 times. This could be a real time-saver when writing code. For instance, if the Webmaster's e-mail address needs to be displayed in various places in a site, storing the address in a variable and then displaying the value of that variable would mean that if the Webmaster's e-mail address changed, the value of the variable would need to be changed only in the one place where it is set, as opposed to having to change every place where the address is used.

A second reason for using variables is that you may not know what the value of the variable is going to be. One of the more common uses of this is when you are accepting input from a user, usually through an HTML form. Variables can be used to verify the user input, insert it into a database, mail it to someone, or perform whatever other processing you need to do.

Creating Variables with <cfset>
You can create variables in ColdFusion using the <cfset> tag. The <cfset> tag takes this form:

<cfset variableName = value>

As with all ColdFusion tags, it starts with the name of the tag, <cfset>. After that you specify the name of the variable that you want to create. Then comes the equal sign, followed by the value you want to give the variable.

ColdFusion has some special conventions that you must follow when chosing a variable name. If you do not follow these rules, ColdFusion will display a nasty error message when you try to execute a template. These are the rules:

  • The first character of a variable name must be a letter, a dollar sign ($), or an underscore. If backwards compatibility is a requirement you should stick with an alpha character (a letter). The underscore and dollar signs work only in ColdFusion MX or BlueDragon.
  • The remaining characters can be made up of any number of letters, numbers, dollar signs, or underscore characters. You are more than welcome to mix upper- and lower-case letters as part of a variable name.
  • Variable names cannot contain a space.
  • Variables cannot include reserved characters or words. This includes punctuation marks (other than underscore and dollar sign) such as the double quotation mark (") and names of tags or built-in functions. The full list of reserved words can be found at http://livedocs.macromedia.com/coldfusion/6.1/htmldocs/expressi.htm.
Within the scope of these few rules, you are wide open to name your variables in whatever way you please. I would always recommend that you try to choose descriptive names for your variables. The X and Y you used to name variables in algebra will not be as helpful as values like Username, FirstName, or Password; especially when you have to revisit your code six months after writing it to make some enhancements.

A variable can hold many different types of values. They can take simple values such as integers, real numbers, strings, or Booleans. An integer is a whole number, such as 12 or 205. A real number is a number with a decimal, such as 12.5 or 19.3. Strings are text values such as "This is a cfset example." Strings are always placed inside quotes, while numeric values are not. A Boolean value has one of two possible values, true or false. In CFML, the words "true" and "false" and "yes" and "no" are Boolean values. A number can also be used as a Boolean value - zero is false and all other values are true.

Complex values such as arrays, structures, or ColdFusion Components can also be assigned to variables with the <cfset> tag. We'll reserve the discussion of complex values for a future column. An expression can also be contained in the value portion of the <cfset> tag. ColdFusion will execute the expression and use the result as the value of the variable. We'll reserve an in-depth discussion of ColdFusion expressions for another article. Right now you can refer to the Macromedia documentation to learn more: http://livedocs.macromedia.com/coldfusion/6.1/ htmldocs/cfml_b14.htm#wp1160241.

Creating Some Variables
With an understanding of creating variables, here's some code that will create a few variables using the <cfset> tag:

<cfset FirstName = "Jeffry">
<cfset LastName = "Houser">
<cfset Age = 28>
<cfset State = "California">
<cfset State = "Connecticut">
<cfset State = 28>

The first line creates a variable called FirstName with a string value of Jeffry. The second variable creates a variable called LastName with a string value of Houser. The third creates a variable called Age with an integer value of 28. Then we create a variable called State and give it the value of "California". The next line changes the value of the state variable from "California" to "Connecticut".

The final line of the code segment changes the state variable's value from a string to an integer. This is an example of changing a variable's type - something that's very easy to do in ColdFusion. This is different from the way many other programming languages operate, and is part of the reason why ColdFusion is very easy to work with. You can easily change a value from an integer to a string and back just by placing another <cfset> tag.

Outputting (Displaying) Variables
Now that you've created a bunch of variables, what do you want to do with them? There are an unlimited number of things that you can do with variables, many of which I'll cover in future columns. In this column we'll just show a simple example of outputting a variable. We can do this with the <cfoutput> tag and a ColdFusion expression.

<cfoutput>
#FirstName#<br>
#LastName#<br>
#Age#<br>
#State#<br>
</cfoutput>

Before going too much further, I want to specify that this code segment must be put in the same template as the previous code segment to execute properly. This listing starts with the <cfoutput> tag. When the ColdFusion server sees the <cfoutput> tag, it knows to process all the text between the beginning <cfoutput> and the end </cfoutput>. The difference between the start and end tag is that the end tag has a slash before the tag name. This is identical to the way that HTML handles start and end tags. Not all tags have both a start and end tag. The <cfset>, for instance, has no closing tag.

You can place any sort of text that you want in the <cfoutput> tag block. The way to tell ColdFusion the difference between normal text and an expression that is to be evaluated is with the use of the pound sign, "#". Text between two separate pound signs is evaluated as an expression. Make sure that there are no spaces between the pound signs and the expression. Any text without pound signs is completely ignored by the ColdFusion server and is passed on to the browser unmodified. This text could be HTML, JavaScript, CSS, or any plain text.

The second line of the template contains a ColdFusion expression and an HTML tag. ColdFusion will look at the expression and return the value of the FirstName variable, "Jeffry". The HTML <br> tag will go straight to the browser. The same happens for the LastName, Age, and State. The code segment finishes with the end cfoutput tag. The output should look like this:

Jeffry
Houser
28
28

You'll notice that the State variable contains the most recent value it was set to, and the other values, "California" and "Connecticut", are lost.

Variable Scopes
At this point, you should have a good understanding of how to create variables within ColdFusion. There is one more important topic you'll need to understand about variables. This is the concept of variable scopes. A scope is used to define the extent of a variable's life before the server destroys it (removes it from memory), and determines how it can be used. To access a variable in a specific scope, you can specify the scope before the variable's name, and separate it from the variable name with a period, like this:

ScopeName.VariableName

Just as you could mix case sensitivity with variable names, you can also do so with variable scopes. They are not case sensitive. Here are some common variable scopes:

  • Variables: This is the local variable scope of a page, the default scope ColdFusion stores variables in, and the first place ColdFusion will look for variables whose scope has not been specified. It is available throughout the execution of a single template and all the include files that the template uses. It is not available to custom tags or ColdFusion Components called from within the template.
  • Request: The request scope is very similar to the local variable scope, except that it is available across a whole request, including inside custom tags or ColdFusion Components called from the main template.
  • Form: When you use an HTML form, its values are placed inside the form scope on the form-processing page. The life of the form scope is a single template execution. Like the request scope, it will be available to custom tags or ColdFusion components.
  • URL: The URL scope contains variables specified in the query string portion of a URL. They have a life similar to the form and request scopes.
  • Cookie: The cookie scope refers to variables that are stored by the user's Web browser. These variables are available during a single template's execution, in much the same way that form, URL, and request scopes are. However, unless you do something to erase a cookie variable from the user's browser, the value will be available on all page requests.
  • Application: The application scope is unique to a particular ColdFusion application. You can set up a ColdFusion application using the cfapplication tag. You can read more about the cfapplication tag at http://livedocs.macromedia.com/coldfusion/6.1/htmldocs/tags-pa3.htm. The application scope is known as a persistent scope, because it exists between page requests. An application variable will exist once, no matter how many users are using your application.
  • Session: The session scope is another persistent scope. A single session exists for each user of a particular application. Just like the application scope, session usage is set up using the cfapplication tag. A different set of values in the session scope will exist for each individual user on your application.
This is a list of some of the more commonly used scopes, but it is not comprehensive. You will most likely discover more scopes during your development adventures in ColdFusion.

In our code example from the previous section, we did not specify a variable scope. When no scope is specified, the variables are placed in the local scope, which is named "variables". We could easily rewrite the previous listing to look like this:

<cfoutput>
#variables.FirstName#<br>
#variables.LastName#<br>
#variables.Age#<br>
#variables.State#<br>
</cfoutput>

This code segment works identically to the one that did not specify the variables' scope before the variable name.

Conclusion
Variables will be the basis of many of your programming projects within ColdFusion. This article should have given you a strong introduction to creating ColdFusion variables, and an overview of some of the uses they provide. In my next column, I'll take an in-depth look at ColdFusion expressions. If there's something you'd like to see in this column, feel free to drop me a line to let me know.

About Jeffry Houser
Jeffry Houser has been working with computers for over 20 years and in Web development for over 8 years. He owns a consulting company and has authored three separate books on ColdFusion, most recently ColdFusion MX: The Complete Reference (McGraw-Hill Osborne Media).

YOUR FEEDBACK
David Kinkead wrote: Good info, but I believe you are completely correct about textual data not being a threat. Let's say you coded in a file named test.cfm: SELECT * FROM sometable where field1 = '#preservesinglequotes(url.name)#' Then a user put in this url: http://yoursite.com/test.cfm?name=ttt';insert into sometable(field1,field2)values('xxx',99998);select * from sometable where field1='x The result is sql injection. I have tested this and know it to be true. However this will only work if you use "Preservesinglequotes", which I have used many times. So we must protect ourselves even with textual data.
Luis Melo wrote: Our system was not SQL Injection proof and we recently suffered an attack that corrupted the data in some of our database tables. The attack was quite elegant and fortunately did not cause severe damage other than the appending of a SCRIPT sting to a bunch of VARCHAR fields. This was meant to actually execute a JS file and this qualifies as a XSS attack. In researching the Web for a solution for the problem, and a way to immunize our CF application against further attacks, we came across the CFQUERYPARAM solution, but our application has over 5000 files, each with one or more Queries and Stored Procedure calls. Implementing such a solution in such an extensive amount of files was impossible in a timely fashion, so I looked for another solution and came across a ColdFusion written function (isSqlInjection) that showed some promise but some shortcomings as well. I wanted something th...
Angela wrote: Isn't WHERE id = #Val(url.id)# just as effective as using cfparam or cfqueryparam?
Will wrote: Hi, I really enjoyed your article about injection attachs, but you forgot one small detial. Even if you use cfparam, it appears that you are still vuneralbe to injection attachs via forms. someone could fill a form filed with some thing like this "# #drop table" the first and last quotes seperate your statement from and move it ouside of the forms "quoes" and thene the the next two #'s creat and execute a new statement.
CFDJ News Desk wrote: Ben Forta's ColdFusion Blog: SQL Injection Attacks, Easy To Prevent, But Apparently Still Ignored. I was just on a web site (no, not a ColdFusion powered site, and no I will not name names) browsing for specific content. The URLs used typical name=value query string conventions, and so I changed the value to jump to the page I wanted. And I made a typo and added a character to the numeric value. The result? An invalid SQL error message.
CFDJ LATEST STORIES . . .
SQL Injection attacks are one of the easiest ways to hack into a website. One recent hack, using a script from verynx.cn, involves injecting sql into a web form that then appends some JavaScript code into fields in a database that then gets executed on the client side when a user views...
Mike Neil is general manager for virtualization strategy in the Windows Server Division at Microsoft. Mike is focused on the delivery of the Windows virtualization technology, including Windows Server 2008 Hyper-V, Microsoft Hyper-V Server and Virtual PC 2007. Mike also directs the tec...
Two of the biggest launches in Rich Internet Application history took place in 2007/2008 when Adobe launched AIR 1.0 in February '08 and Microsoft launched Silverlight (September '07). At the 6th International AJAXWorld RIA Conference & Expo in October SYS-CON Events is delighted to be...
Recursion Software released a private beta version of their Voyager mobile platform, with powerful interoperability for Android, Microsoft .NET and Compact Framework (CF), all Java editions (JME CDC, JSE and JEE), and more than 15 embedded operating systems. The Voyager platform is a p...
2008 is going to be an important year for Rich Internet Applications. Most organizations are delivering or planning to deliver Rich Internet Applications; however, at the same time, most IT managers are facing a dilemma: which Rich Internet Application technology and platform to use? T...
CFDynamics, a ColdFusion web host, has renewed an agreement with SmarterTools that will allow them to pass on immediate value to their customers. When a customers signs up for a dedicated hosting account they will now receive $750 worth of features including SmarterMail, SmarterStats a...
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021


SYS-CON FEATURED WHITEPAPERS

ADS BY GOOGLE