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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With