How to prevent errors when session times out

Posted on 2004-10-01
Medium Priority
Last Modified: 2013-12-24
My CF application relies heavily on session variables to construct URLs. If the user leaves the browser for the timeout period and then attempts one of these links or forms, they will get an error after being routed to the login page because the needed session variables have been lost.  

I realize that I could check for the presence of each of these session variables every time, but this would be a huge job and would require different logic in each case.

I'm looking for possible solutions that would let me simply redirect to the home page when a session timeout occurs, rather than trying to honor the original request. The problem is that the URL to the home page itself is dynamically constructed using a session variable to identify the path e.g. http://hostaddr/<session.yourpath>/index.cfm

My request then is for any ideas to present a more graceful redirection on session timeouts.  

Question by:451ls
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 21

Expert Comment

ID: 12205831
good suggestion from http://www.experts-exchange.com/Web/WebDevSoftware/ColdFusion/Q_21099604.html
 Option 1: To be able to tell whether a session timed out, you have to set a variable somewhere where it will "survive" the session timeout. That is anywhere but the session scope. You could use the application scope, client- or cookie scope (if you use persistent cookies) or a table on the database or even a plain and simple text file.
You store the session ID and timestamp.
Now, whenever you detect a new, empty session, you check whether the session ID is present in that other storage and its timestamp is somewhere between your default session timespan and a couple of hours or whatever is a safe timespan to assume it's a user returning from lunch ;)
Yep, there's the word 'assume', so it's not a waterproof method.

Option 2: Use javascript: setTimeout('aFunction()', x);
x = your session timespan in milliseconds
aFunction = javascript function that does a redirect to the loginpage with an extra flag in the URL that lets you know it was a session timeout.
This way if a user stays on a page long enough for the session to timeout, he/she will be redirected to the login page and you'll have a url.sessionTimedout variable.


Expert Comment

ID: 12207714
Two comments..

From a "best practices" approach, if you are using session variables throught out your app, then you should set a session var that would be the same for all pages, like session.isloggedin or session.sessionExists. Then you only have to check for the existence of this one session var and not all session vars (assuming that you have logic in place on each page that checks for the existence of specific session vars before they are called). This also assumes that you have set up your session to expire whenever the browser is closed (cf does not do this automatically, you have to do this in your application.cfm).

This "session exists or isloggedin" var would be set on the homepage or login page. At the top of every page, then check to see if it is or is not defined and then process the page accordingly.

With this in placy, attemps to access any page when the session var is not defined sends the user back to the login page. This also prevents your page from showing errors if a user logins and bookmarks some internal page and later tries to access it via the bookmark or favorite. Here is some example code...

<cfapplication name="sTracker"

<cfif Not IsDefined('session.loggedIn')>
      <cflocation url="login.cfm">

On your login page, after you have verified the user via your login validation logic, the set the session var...
<cfset session.isloggedin="yes">

In your post it is unclear how "<session.yourpath>" is set. If there is a log in process so based on a user logging in they get a different "<session.yourpath>" then you could set a non-persistent cookie for the path variable. Something like this..

After a user successfully logs in instead of coding something like
<cfset session.yourpath = "somepath">
<cfset cookie.yourpath =

Expert Comment

ID: 12208180


Please ignore the stuff just below the <cfapplicaton...> tag and I will try and continue where I left off before my fat fingers get in the way again...

Learn how to optimize MySQL for your business need

With the increasing importance of apps & networks in both business & personal interconnections, perfor. has become one of the key metrics of successful communication. This ebook is a hands-on business-case-driven guide to understanding MySQL query parameter tuning & database perf


Accepted Solution

dldeeds earned 500 total points
ID: 12209575
Back again, right after typing the above, my ISP went down... so here is the rest of what I was going to comment on..

Now where was I...oh yeah..Example cfapp with session destroyed on browser close..

<!--- cfapp with no client management --->
<cfapplication name="myApp"
               sessiontimeout="#CreateTimeSpan(0,0,0,10)#"> <!--- set time out to 10 seconds for testing --->

<!--- set "local" or memory cookies which will go away when browser is closed --->
<cfif IsDefined( "Cookie.CFID" ) AND IsDefined( "Cookie.CFTOKEN" )>
  <cfset localCFID = Cookie.CFID>
  <cfset localCFTOKEN = Cookie.CFTOKEN>
  <cfcookie name="CFID" value="#localCFID#">
  <cfcookie name="CFTOKEN" value="#localCFTOKEN#">

<!--- on login page or home page set "session exists" variable after user has been validated --->
<cfset session.sessionExist="yes">

<!--- at the top of every page check for the session exists var and redirect if not --->
<cfif Not IsDefined('session.sessionExists')>
<cflocation url="index.cfm" addtoken="no">

You are using a session var to determine which path a user will go to when their session times out. Sort of a Catch-22 thing. I don't know how you originally set the "<session.yourpath>" variable, but I assume you have some kind of log in or logic that says "user1" goes to something like  http://hostaddr/user1/index.cfm and "user2" would go to  http://hostaddr/user2/index.cfm , etc.

You can change your "session.yourpath" to "cookie.yourpath" after validating the user on login.

<cfset cookie.yourpath = "sompath"> sets a non-persistent cookie, that is a cookie that is "written" to the clients browser memory and not their harddrive cookie storage area. This cookie is destroyed on browser close just as a session is (if you set up your session to do so) but will persist past the session time out. So when your session times out you can still check to see if "cookie.yourpath" exist, check its value and send the user somewhere based on that value.

Just this week I implemented a similar scenairo on one of our websites. I had avoided looking at the <cfcookie> tag becuase I did not want to "write" a cookie, but then learned that <cfcookie> or using a <cfset cookie.somevar> does not write that to the harddrive but keeps it in memory (at least for cfmx 6.1).

On our page I wanted to place a message for the user that their session had timed out. So I did a Not IsDefined check, the only thing, the first time in, the user got the "your session has timed out" message before they even logged in (I was setting the session vars after login). So I created a a var called "cookie.sesdef" and "session.isloggedin" after the user passes the login validation checks. Then on the home page, if "session.isloggedin" in is not defined and "cookie.sesdef" is not defined then the user gets a standard "Welcome" message, but if "session.isloggedin" is not defined and cookie.sesdef is, then I know that the user has logged in and their session has timed out and I redirect them to the login page (checking for session on every page) and giving them a session time out message.

Hope this helps....and sorry about the "fat fingers" slip up with the first post.
LVL 17

Expert Comment

ID: 12210233
what dldeeds suggest is definately a good practise. Another way of doing it using <cferror> or cftry and cfcatch to catch all errors, then you see if the error message contains keywords like SESSION and undefined or something, based upon that you can assume that the session expired and redirect them to the login...

Author Comment

ID: 12211969
To dldeeds,

Your comment 2 hits my problem dead on. I did not know that cfset cookie.var stored the value in the browser memory. I also encountered exactly the problem you did of having the session timeout message come up the first time the user comes to the site, so I was amazed you had an answer for that as well.

Yes, your analysis of how I set the program path is exactly correct.

Great job of figuring out my problem.

Featured Post

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Meet the world's only “Transparent Cloud™” from Superb Internet Corporation. Now, you can experience firsthand a cloud platform that consistently outperforms Amazon Web Services (AWS), IBM’s Softlayer, and Microsoft’s Azure when it comes to CPU and …
When it comes to security, close monitoring is a must. According to WhiteHat Security annual report, a substantial number of all web applications are vulnerable always. Monitis offers a new product - fully-featured Website security monitoring and pr…
Michael from AdRem Software outlines event notifications and Automatic Corrective Actions in network monitoring. Automatic Corrective Actions are scripts, which can automatically run upon discovery of a certain undesirable condition in your network.…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …
Suggested Courses

741 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question