views:

51

answers:

3

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 append it to the end of the URL address bar.

END EDIT

+1  A: 

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"]);
Pekka
And *HTTP\_HOST* is really just the host.
Gumbo
@Gumbo arrgh! :) It's time for lunch. Cheers. I cut it down to the absolute path for the moment.
Pekka
Don’t forget the sanity check. ;)
Gumbo
@Gumbo do I need a sanity check here? Maybe it's indeed my low blood sugar, but I can't think of one. The only danger that comes to mind is escaping from the `header()` but that is fixed in PHP 5. Anything else to look out for? If there is, I asked a related question some time ago that could use the input: http://stackoverflow.com/questions/2209894/sanitation-for-url-used-in-header-location
Pekka
Thanks for this. Deal with GET requests all the time so no idea why this idea didn't come to me!
baswoni
A: 

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!

Macros
+1  A: 

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.

SilentGhost