Please consider a donation to the Higher Intellect project. See or the Donate to Higher Intellect page for more info.

Session management in ColdFusion

From Higher Intellect Vintage Wiki
Jump to navigation Jump to search

Maximizing cookies, session variables, and URL-appended values

Many technologies, such as PHP, ASP, and Domino, can help you manage sessions on your Website. In this month's Webmaster, Danielle Anthony and Bryan Formidoni concentrate on Allaire ColdFusion, an application server that enjoys a broad developer base. With cross-platform compatibility, ColdFusion creates a controllable, session-based environment.




By Danielle Anthony and Bryan Formidoni

Sessions, or requests that a single user makes to a server, are one way to measure your Website's traffic. They are unique to each visitor, and although sessions are inherently anonymous (no personal identification is required), they can be useful in tracking and reporting traffic as well as in personalizing your site. Sessions can be used to generate display preferences, such as background colors or font faces, as well as content preferences, such as feature stories, local news, or stock quotes. Once determined, such preferences will persist through every page on the site.

Sessions start and end when the user enters and exits, respectively. A session may also end if the browser is idle for a significant amount of time. To track visitors, certain variables are assigned to a user -- perhaps a unique userid is associated with the contents of a shopping cart. That userid is passed along to every page the user views so that the displayed cart is accurate. Sessions can also be used to deliver dynamic content based on a visitor's profile, assuming a voluntary registration form has been completed.

Suppose a visitor to a portal site selects local news as a primary area of interest when filling out a registration form. That information could be used to generate navigation links throughout the site. Likewise, if a visitor enters a preference for stock quotes, every navigation template could incorporate a link to stock quotes. The site is not only personalized but also remains personalized throughout the session.

Session variables versus application variables
The focus of this article is on sessions and session-based variables, not on application variables. It's important to differentiate between the two. The goal of session variables is to maintain the state of a site without setting multiple cookies or making numerous calls to a database. The most significant difference between session variables and application variables is in scope. As stated earlier, sessions are attached to each unique visitor. Application variables are attached to an entire site or application.

You can set or call session variables anywhere in the site and they will be applicable to one specific visitor. Conversely, application variables are set once on the server and can be called anywhere in the site, regardless of the visitor. Consider setting an application variable for a copyright stamp to be displayed on all navigation footers. The first step is setting a variable called copyrightdate to 2000 in the Applicaton.cfm page. You can include that value on any page within the site by referencing #application.copyrightdate#.

		Copyright #application.copyrightdate#, all rights reserved.

That would output the following to the browser:

Copyright 2000, all rights reserved.

You can think of application variables as small server-side includes (SSIs) that exist independently of session variables. They are invaluable in maintaining sites where small pieces of content change frequently, and advantageous because they place less load on the server than multiple SSIs.

Tracking sessions in ColdFusion
Allaire ColdFusion gives you three ways to track sessions: session variables, cookies, and values appended to the end of URLs. Each approach requires the creation of a unique identifier for each visitor. Although ColdFusion writes a cookie with a system-generated unique ID, it's not practical to reference that variable. Instead, we generate a unique ID from an algorithm that we define. The algorithm used to generate this ID varies, but it often includes combinations of a time stamp, a counter, and a random number. We'll refer to that variable as userid in the following descriptions of the session-management options.

Session variables
To effectively deploy session-management variables in ColdFusion, configure the application server to accept and monitor them. A <cfapplication> tag must be added to the Applicaton.cfm page:

<cfapplication name="myName"
SessionTimeOut ="#CreateTimeSpan(0,0,120,0)#">

Those tags tell ColdFusion to do two things: enable session management and set the timeout after 120 minutes. While the default timeout is 20 minutes, it can easily be reset in the ColdFusion administrator. Note that the timeout setting in the Applicaton.cfm page overrules the administrator setting.

For different applications you may want to lengthen or shorten that amount of time. For example, a high volume e-commerce site such as would probably not want a long timeout, for fear of draining the system resources, especially considering that people often fill up a cart without purchasing the items in it. Because we cannot actually tell when a user leaves a site and points the browser to another Website, timeouts are necessary.

On the other hand, there are disadvantages to setting a short session timeout. First, the user will have to return to a specific page to start a new session, and second, that person will lose the display or content preferences established within the previous session. You might experience this aggravation yourself when you place products in an online shopping cart and then leave your computer. When you try to continue shopping or to actually purchase the articles, the Buy Now button gives you an error message, informing you that your session has expired.

After the timeout tag has been added to the Applicaton.cfm page, session variables can be set and retrieved from anywhere in the application. Many sites set the variables on the homepage, but you may want to set them on the first shopping cart page or on the registration page. Below is an example of setting a session variable. It is no different from setting other variables in ColdFusion:

<cfset session.userid= "myUniqueValue">
To retrieve that variable, reference it with session scope:

An effective way of using session variables is to check for their existence when the page is generated. A variable can be set to true or false, based on the existence of the session variable, and then be called lower in the page for conditional processing:

<cfif parameterExists(session.userid)>
	<cfset sessionYes  =  "true">
	<cfset sessionYes  =  "false">

This way, you reference the session variable only once during page processing. Suppose, for example, you're generating a page that serves dynamic navigation along the top and left side, and dynamic content within the body. The server-side code conditionally processes the page based on the registered user's profile. Instead of calling to the session variable for every piece of dynamic content, the local variable is called from each section. The processing time is decreased.

This method would also apply to verifying the existence of cookies. It's much more efficient to sniff the cookie once per page than to make multiple call references to it.

One benefit of utilizing session variables in ColdFusion is that they are simple to develop and deploy. But they do have drawbacks. Session variables use significant system resources. High-volume sites may prefer to use other means of session management to cut down on the system overhead. Session variables also require that a cookie be set on the visitor's machine, which is a problem for developers who want to track cookie-phobic people or employees of companies that don't allow cookies to be set.

ColdFusion assigns the cftoken and cfid values to the cookie within the session variable. Those are unique identifiers that the application server uses, and they are not usually referenced by programmers. If a user returns to the site, the values are reset and the cookie is overwritten.

As mentioned above, cookies are an alternative to session variables. They're not as flexible, but they can manage user sessions. Cookies are useful to the browser because they store a visitor's information, like usernames and encrypted passwords, as well as shopping cart items or past purchases. They are useful to the developer because they cut down on the number of human hours necessary to fill databases. In ColdFusion, use the <cfcookie> tag to set a cookie on the client machine (client-side variable):

<cfcookie name = "userid"
value = "myUniqueValue"
expires = "10"
secure = "Yes/No"
path = "/myDirectory/"
domain = "">

As with session variables, you can check for the existence of the cookie on each page and conditionally process:

<cfif parameterExists(cookie.userid)>
	<cfset cookieYes  =  "true">
	<cfset cookieYes  =  "false">

Variable appended to the URL
If it is imperative to manage sessions without using cookies, you can append a variable value pair to the end of all the URLs in the site. For example:

<a href="">

When the visitor arrives at the site, the userid is set to a unique value. It is then passed along to all URLs within the site. Because this solution does not require cookies, it's the most common one. However, it also poses a much greater security risk. Because the visitor's ID is always visible in the location bar, a manual change to the URL by a visitor could reveal another visitor's session. Developing a more complex or random algorithm within the userid might reduce the risk.

So what would we do?
If we had to choose how to track a client (one unique browser that persists over multiple sessions), we'd use a combination of session variables and cfcookies. We wouldn't want to use cookies alone. If a machine is shared and more than one user has browser access, such as in a public library or computer lab, cookies can't accurately track an individual. They are no longer unique.

Also, many users have a laptop at home and a desktop computer at the office. So if someone at work puts a book in a shopping cart (say, at to order later at home, the book has to be located again on the site. It won't automatically be available for purchase. Session variables alone can't personalize frequent visits, because they end when the browser is closed. But when combined with cookies, session variables can use browsing and buying habits to determine the dynamically generated content. It's no coincidence that each time we visit certain Websites, new ColdFusion or design books are highlighted. They know what kinds of books we buy and that we buy multiple copies. Needless to say, purchase histories can be quite valuable for cross-selling in e-commerce sites.

Maybe you don't have an e-commerce site and couldn't care less about a user's purchase history. But you might be responsible for measuring specific events that occur on your site. For example, what if the vice president of human resources approached you, wanting to know the specific ratio of the jobseekers visiting your site to the number of jobs available, or to the résumés submitted? The combination of cookies and session variables would provide answers to such specific questions. The old method of hit counting and page viewing couldn't give accurate answers.

One final note: Traffic measurement can be a valuable tool not only for the VP of human resources, but also for you. We once wanted to show that a certain homepage would generate more leads (the visitors completed a form for a salesperson to call them). A manager insisted on another version of the homepage only because he liked it. We randomly served both versions, measured the length of sessions, tracked the events, and proved that the original homepage indeed generated more leads. Taste and style may vary, but managers know that numbers don't lie. Which, in this case, was good for us.