• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 559
  • Last Modified:

PHP - Login Include redirect to initial page

Dear Experts,

I've implemented a login include at the top of each of my pages.
When a user tries to open this pages it will first check whether he has been logged in, using $_SESSION's,
and if not, the user is directed to the login page.

This is working as expected up till here. But what I would like to have is when the user tries to open a page the login include must direct the user to the page he was initially trying to open after the login was successful.

Hope this makes sense..

Kind regards
4 Solutions
You could use $referer = $_SERVER['HTTP_REFERER']; to store the referring page and then redirect to it.

This can also be done with JavaScript using the history code.
header('Location: '.$_SERVER['HTTP_REFERER']
In that case you need to give the redirect a variable location. You can usually find the last page visited in $_SERVER['HTTP_REFERER']. This is not complety reliabe and there are other methods, but could you post the corresponden code please ? Than I could help you further.
Alternative method is passing the origin url in a GET variable.
I answered a question with this method some days ago here
Improved code regarding the answer above (this is, passing the referrer URL as a GET variable)

// Code for redirecting an non logged in user to login page
$loginurl = 'login.php';
header('Location: '. $loginurl . "?from=" . urlencode($_SERVER['PHP_SELF']));
// Code for redirecting a logged in user to referrer page
header('Location: ' . urldecode($_GET['from']));

Open in new window


Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now