How to redirect users after login in PHP is easy to pro web developers but not new web developers learning redirects, sessions and variables
If you Google how to how to redirect users after login in php you will be get https://stackoverflow.com/questions/24476899/how-to-redirect-after-successful-login-php as the best answer, however this https://aarafacademy.com/redirect-back-referral-page-login/ would be the preferred solution.
How to redirect users after login is hard?
There are many factors to look at before seeing the challenge before you.
Redirecting users requires using sessions, $_SERVER[“PHP_SELF”] and header variables some new developers may never have any idea about.
Say you are designing a website and you have four web pages i.e. login.php, admin.php, profile.php, home.php
The pages admin.php, home.php and profile.php can only be accessed after logging in, how do you redirect the user back to profile.php once they try to access it directly.
By design you could simple add a redirect to the login.php which granted the user access to home.php or admin.php which the user may not like.
How to redirect users after login in PHP?
The best solution would be to add a $_SESSION[“login_redirect”] = $_SERVER[“PHP_SELF”]; variable to all the pages that must be accessed after login.
You could add the following to your header section of admin.php, profile.php and home.php;
<?php
//Start session
session_start();
//Check whether the session variable ‘verifiedUser’ is present or not
if (isset($_SESSION[‘verifiedUser’]) && $_SESSION[‘VerifiedUser’] == true) {
echo “”;
}
else {
//redirect the user to the login page from here
$_SESSION[“login_redirect”] = $_SERVER[“PHP_SELF”];
header(“Location: login.php”);
exit;
}
?>
Once you have done that go to the login page and add the following;
<?php
if (/* Login is successful */) {
// Do whatever it is you have to do to finish the login…
// Then check if the login_redirect is set, and use that.
// Otherwise just redirect back to home.php.
if (isset($_SESSION[“login_redirect”])==true) {
header(“Location: ” . $_SESSION[“login_redirect”]);
// And remember to clean up the session variable after
// this is done. Don’t want it lingering.
unset($_SESSION[“login_redirect”]);
}
else {
header(“Location: home.php”);
}
exit;
}
?>
This works pretty well in scenarios of single users, where you don’t have to worry about the admin login.
In case you need to cater for the admin then you have to add extra checks in the admin header page, alternatively you could add a variable in the login.php to cater for the admin.