How to prevent errors when session times out

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.  

Who is Participating?

Improve company productivity with a Business Account.Sign Up

dldeedsConnect With a Mentor Commented:
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.
good suggestion from
 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.
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 =
Easily Design & Build Your Next Website

Squarespace’s all-in-one platform gives you everything you need to express yourself creatively online, whether it is with a domain, website, or online store. Get started with your free trial today, and when ready, take 10% off your first purchase with offer code 'EXPERTS'.



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...

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...
451lsAuthor Commented:
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.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.