PHP redirect back to previous page

20,000

Solution 1

  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.

Solution 2

$_SERVER['HTTP_REFERER'] depends on the Web Browser, not all browser sends the referrer back to the server. A better approach, used by many big sites, is passing on the current page to the login page:

header("Location: first.php?".$currentPageUrl);

The $currentPageUrl can be get from the $_SERVER['REQUEST_URI'] or $_SERVER['PHP_SELF'];

Upon login you can redirect user to the $currentPageUrl again.

Apart from this, it does not sound right to store the user name and password in the $_SESSION, but this is a separate issue.

Share:
20,000
Andrew Liu
Author by

Andrew Liu

Updated on June 04, 2022

Comments

  • Andrew Liu
    Andrew Liu almost 2 years

    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.