Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Returning a user to their original page after login

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.

like image 367
AgentConundrum Avatar asked Dec 29 '22 06:12

AgentConundrum


1 Answers

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.

like image 76
mauris Avatar answered Jan 05 '23 16:01

mauris