Using $_SERVER['HTTP_REFERER']
is dangerous because the referrer will be the same login page if the user received an error while trying to login (for example, as an incorrect password). You must save the return URL inside the session variable before redirecting the user to the login page, and then after successful login, redirect them to the saved return URL.
For example, let's 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 can fill in the variable $_SESSION['user']
, and then redirect to the URL that you saved before sending it to the login page (or to the root of the site, if this is so, t have any return url stored for any reason):
$backURL = empty($_SESSION['backURL']) ? '/' : $_SESSION['backURL']; unset($_SESSION['backURL']); header('Location: ' . $backURL); exit;
source share