Home » Php » php – Sending user back to referring page

php – Sending user back to referring page

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am struggling to set up a redirection after successfully logging in by user.

The login page should redirect the user to the page where they were refused to access after they have successfully logged in.

For example, if a user clicks on ‘My Account’ before logging in (no session) then they are redirected to login page successfully but once they are logged in, how do I send them back to the “My Account” page?

Methods I tried include $_SESSION['HTTP_REFERER].

Any help would be much appreciated.

How to&Answers:

Using $_SERVER['HTTP_REFERER'] is dangerous, since the referrer would be the same login page if the user received an error while trying to login (such as wrong password). You should store the back URL inside a session variable before redirecting the user to the login page, then, after they successfully log in, redirect them to the stored back URL.

For example, say you need to protect page.php, you could have something like this at the beginning of the file:

if (empty($_SESSION['user'])) {
    $_SESSION['backURL'] = $_SERVER['REQUEST_URI'];
    header('Location: login.php');
    exit;
}

Then, after the user successfully logs in, you could populate the $_SESSION['user'] variable then redirect to the URL you stored before sending him to the login page (or to the root of the site if it so happens that you don’t have any back URL stored for whatever reason):

$backURL = empty($_SESSION['backURL']) ? '/' : $_SESSION['backURL'];
unset($_SESSION['backURL']);
header('Location: ' . $backURL);
exit;

Answer:

Try this:

<?php
  header("Location: " . $_SERVER["HTTP_REFERER"]);
?>

Answer:

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

session_start();
if (!$logged_id)
{
    $_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;

Answer:

header("Location: " . $_SERVER["HTTP_REFERER"]);

Will do it, but note:

You CANNOT output (echo,print_r,ect ect) anything before sending custom headers.

Answer:

You should remember last visited page in variable like $_SESSION["last_page"] (exclude login page). After user successfully was logged in, take value of variable and redirect user to his previous location.

You can’t use referrer. For example, if user failed his first attempt to login, in second attempt his referer will be login page.

Another way is to authenticate user using ajax without separate login page. If login was successful, you can simply refresh page with javascript.