Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP redirect back to previous page

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.

like image 617
Andrew Liu Avatar asked Nov 18 '25 13:11

Andrew Liu


1 Answers

  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.

like image 155
John Conde Avatar answered Nov 21 '25 03:11

John Conde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!