On login page:
<form action="controller/LoginController" method="post">
<?php
if($_SERVER['HTTP_REFERER']){
echo '<input type="hidden" name="l" value="'.$_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']
.