PHP: Returning a user to their original page after login

AgentConundrum picture AgentConundrum · Dec 31, 2009 · Viewed 7.8k times · Source

Are there any 'best practices' concerning how one should return a user to their original page after logging in to your website, specifically in PHP? e.g. if I'm viewing a StackOverflow question while not logged in, how would you ensure that I return to this question if I logged in?

From my research, it seems a lot of advice centers around the $_SERVER['HTTP_REFERER'] variable. Basically, you take note of the referer and store it in the session, then redirect back to that page when you're done.

The problem with this is that HTTP_REFERER is unreliable at best.

This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
— [http://php.net/manual/en/reserved.variables.server.php]

Any edits to the referer to redirect to other areas of the site will be handled by routine permissions checks. If the referer gets blanked out, it might be acceptable to simply redirect the user to the main page of the site rather than the page they came from. This seems needlessly user hostile though, and I was hoping there would be some better way to handle this.

Answer

mauris picture mauris · Dec 31, 2009

On login page:

<form action="controller/LoginController" method="post">
<?php

if (isset($_SERVER['HTTP_REFERER'])) {
  echo '<input type="hidden" name="l" value="'.htmlspecialchars($_SERVER['HTTP_REFERER']).'" />';
}

?>
<!-- the rest of the form -->
<input type="submit" />
</form>

At login controller, you take in the $_POST['l'] value and see whether or not this URL is on your own website. If it isn't, redirect to your default page, else redirect to this URL.

Make sure that on your login page if user is already logged in, you redirect the user back to home page or something. This will prevent cases like redirecting back to login.

$_SERVER['HTTP_REFERER'] is a browser responsibility. It is also most of the time rather reliable. If the browser doesn't send, or if you are worried about it, you can use session instead.

on every page simply set $_SESSION['lastvisitpage'] to the current page URL. On login then you redirect to $_SESSION['lastvisitpage'].

Since $_SERVER['HTTP_REFERER'] can be faked by a user at any time, one should always treat is any other user-supplied variable by properly escaping it.