We help IT Professionals succeed at work.

PHP - Login Include redirect to initial page

Marius0188 asked
Medium Priority
Last Modified: 2013-12-13
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
Watch Question

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.

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
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

Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.