Tuesday, June 24, 2008

Redirect after login

One of my pet peeves is sites that don't redirect you back after you log in. I can kinda understand a developer being too lazy to redirect back after session timeout or bookmark, but when the site sends you an email with a link and after logging in to view the link you get thrown somewhere else, that's completely unacceptable.

Do not send the url the user was trying to reach as a url variable. This is ugly and error prone. Sites that do this, forget to preserve the url if user enters incorrect username or password or tries to retrieve the password.

After verifying that the user is logged in and before redirecting to log in screen, save the current url as a session variable.
<cfset session.fromurl = cgi.script_name & "?" & cgi.query_string />

$_SESSION["fromurl"] = $_SERVER["REQUEST_URI"];

After the user has successfully logged in, assign the url to a variable and delete the session variable and then redirect.
<cfset variables.fromurl = session.fromurl />
<cfset structdelete(session, "fromurl") />
<cflocation url="#variables.fromurl#" addtoken="no" />

if (isset($_SESSION['fromurl'])) {
$url = $_SESSION['fromurl'];


  1. I tried this but CGI.QUERY_STRING and CGI.SCRIPT_NAME only return the url of the current page, not the one the user clicked in an email. You describe the problem perfectly but your solution does not work for me.

    Perhaps it's code placement. I tried to save the url clicked first in my application.cfm page, then the page after that before my login page. This didn't work.

    Please help!!
    Sam (yabassi_online@yahoo.com)

  2. ON you coldfusion example the first example should read

    The session. was omitted
    This helped me out. THKS

  3. Thanks for the heads up.
    Looks like my new layout's making the text invisible.

  4. Useful bit of code, thanks!