Remembering destination when logging in
When I want to redirect a user to a specific page behind a login wall and they're not already logged in, they get redirected to the homepage where they can login. When they login, they are redirected to a default address.
How do I go about remembering where the users original destination, before they were redirected to the login page?
EDITED WITH SOLUTION
Thanks for the responses. What I've done is set a GET request when the user is detected to not have logged in, using the URL: domain.com/?url=$_SERVER["REQUEST_URI"]
So when the user is redirected to the login page, the address that the user tried to get to is set in the GET value. When the user logs in and authenticates, I do a test to see if there's a GET value, if there is, then appen开发者_JAVA百科d it to the end of the URL address bar.
END EDIT
The easiest way is to add the URL of the current page to the login page as an argument:
... not logged in ....
header("Location: loginpage.php?url=".
urlencode($_SERVER["REQUEST_URI"]));
(Note, for this, both scripts need to be on the same domain. If they are on different domains, you'd need to use something like "http://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"]
)
and after login, redirecting to that page:
header("Location: ".$_GET["url"]);
add a variable containing path to page user started logging in. Have a look at how it is done on SO: when you choose to login you're redirected to a page that has a returnurl
parameter, e.g.:
returnurl=%2fquestions%2f3280860%2fremembering-destination-when-logging-in
after successful login you could return user to that page.
You can use $_SERVER['PHP_SELF']
to return the relative path of the current page, and pass it as a querystring parameter to the login page.
For example, your code that checks if a user is logged in could sit in an include file and look like the following:
if(!isset($_SESSION["some variable"]))
{
$login = sprintf("%s?dest=%s", LOGIN_URL, $_SERVER['PHP_SELF']);
header("location: " . $login);
}
on your login page, once the user has logged in you can redirect them to the original URL, which is accessed using $_GET["dest"].
Code is typed from memory and am not able to test until later - it should work however!
精彩评论