PHP redirect back to previous page

Andrew Liu picture Andrew Liu · Jul 25, 2013 · Viewed 19.7k times · Source

What I have done for the login.php page is if a user has logged in, he will be redirected to first.php page.

session_start();
if(isset($_SESSION['usr']) && isset($_SESSION['pswd'])){
    header("Location: first.php");
} 

In all other pages, if user hasn't logged in he will be redirected to login.php page.

session_start();
if(!isset($_SESSION['usr']) || !isset($_SESSION['pswd'])){
    header("Location: login.php");
} 

Here is the problem: is there a way to redirect the user back to where he was from? Say if you are trying to reach second.php while you are not logged in, you will be redirected to login.php page now; once you log in, can you be redirected back to second.php instead of first.php?

I have tried to use $_SERVER['HTTP_REFERER'], but this variable doesn't contain anything; it only contain something if you are here because you have clicked a link.

Answer

John Conde picture John Conde · Jul 25, 2013
  1. On the page they try to login set a session variable containing the URL of that page.
  2. Then redirect them to the login page.
  3. After a successful login get the previous URL from their session and redirect them there.

Have the page that does the redirecting set a session variable that is the URL of that page:

session_start();
if (!$logged_in)
{
    $_SESSION['redirect_url'] = $_SERVER['PHP_SELF']; 
    header('Location: login.php');
    exit;
}

Then after a successful login redirect them to that URL:

session_start();

/* Login code goes here */

$redirect_url = (isset($_SESSION['redirect_url'])) ? $_SESSION['redirect_url'] : '/';
unset($_SESSION['redirect_url']);
header("Location: $redirect_url", true, 303);
exit;

The above can be improved upon but this should give you the idea.