Darius
Darius

Reputation: 1664

Redirect to page user was trying to get to after logging in

Been reading a bit to find the answer with not too much luck.

I have a site where members can browse the site anonymously but some pages are restricted. I have the members redirected to a login page once they click a link that needs them to be logged in to view.

The problem I'm facing is I don't know how to redirect the member to the page they were trying to get to once logged in.

They tried to to get to /profile.phtml , it sent them to /login.phtml , now when they log in, I want them to be sent to /profile.phtml because that's where they clicked to get to. If they clicked /album.phtml, I want them to be sent to /album.phtml after login.

Can anyone help? Do I somehow store the URL in a session?

Much appreciated.

Upvotes: 3

Views: 2193

Answers (2)

vicTROLLA
vicTROLLA

Reputation: 1529

You could very well use a session variable like other people are suggesting. However, I'd rather rely on HTTP_REFFERER. The drawback here is not every browser sends a referrer, but most major browsers do. It's a part of the HTTP standard and I think it's good enough. Stick this in your login script.

if(!empty($_SERVER['HTTP_REFERER'])) { header('Location: '.$_SERVER['HTTP_REFERER']); }

Upvotes: 0

Michael Berkowski
Michael Berkowski

Reputation: 270677

Just before making the header("Location:") call to redirect, store the page they're currently on in $_SESSION['redirect_to']. Upon successful login, make another header() call to redirect back to the original page and unset the session variable so it doesn't get accidentally reused anywhere.

$_SESSION['redirect_to'] = $_SERVER['REQUEST_URI'];
header("Location: http://example.com/login.php");
exit();

// On successful login
$redirect = $_SESSION['redirect_to'];
// unset the session var
unset($_SESSION['redirect_to']);
header("Location: http://example.com/$redirect");
exit();

Upvotes: 5

Related Questions