On the 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']).'" />'; } ?> <input type="submit" /> </form>
In the login controller, you take the value of $_POST['l'] and see if this URL is on your own website. If this is not the case, redirect to the default page, otherwise redirect this URL.
Make sure that on the login page, if the user is already logged in, you are redirecting the user to the home page or something like that. This will prevent incidents such as redirecting to login.
$_SERVER['HTTP_REFERER'] is the responsibility of the browser. It is also pretty reliable in most cases. If the browser does not send, or if you are worried about it, you can use the session instead.
on each page, just set $_SESSION['lastvisitpage'] to the current page URL. When you log in, you are redirected to $_SESSION['lastvisitpage'] .
Since $_SERVER['HTTP_REFERER'] can be tampered with by the user at any time, you should always consider any other user-provided variable if you avoid it.
source share