Ask a Jedi: Sending users back after a logon

This must be security week. Chris asked this:

Is there a simple way to redirect users after login to the page they came from?

Sure is. Let’s use a concrete example from Galleon . Galleon lets users browse the site but they can’t write new posts until they sign in. I wanted to make it so that if you were viewing a thread and decided to login, you would be returned to that thread when done. Here is how I did it.

First I created a variable for the current page:

<cfset thisPage = cgi.script_name & "?" & reReplace(cgi.query_string,"logout=1","")>

Notice that I use the currently query string in order to get any URL variables. However, I use a URL variable to log people out so I have code to remove that. (This may not apply to your own site.) I then create a complete link to the login page:

<cfset link = "login.cfm?ref=#urlEncodedFormat(thisPage)#">

The link contains a URL variable, ref, that is a pointer back to where I came from. My logon form is written to ensure it doesn’t lose any URL variables. On a good logon, I then simply send the user back:

<cfif request.udf.isLoggedOn()> <cfif isDefined("url.ref")> <cflocation url="#url.ref#" addToken="false"> <cfelse> <cflocation url="index.cfm" addToken="false"> </cfif>

Easy as pie, and I’m sure there are a hundred other ways of doing this as well.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Comments