Skip to content
Advertisement

How can I redirect to the next page I clicked after login PHP

Imagine I have a page called index.php and several other pages that are linked to it. Any link on index.php requires logging in to access it. All the links on index.php should redirect me to another page but only after a successful login.

How can I go to any link I clicked automatically after I log in successfully. An example is, when I click on xxxxxxxxxxx.php, it takes me to the login page first and, after I successfully login, I would prefer it takes me to xxxxxxxxxxx.php for that instance.

Advertisement

Answer

I came up with a solution and it works. I’m not quite sure how safe it is but check it out

First, if the person is not logged in I redirect to the login page with the requested page set to $_SERVER['PHP_SELF'];.

if (!isset($_SESSION['user_id'])) {
    header('Location: ../login?next='.$_SERVER['PHP_SELF']);
    $db = null;
    die();
}

Then is the person logs in successfully I set the requested page to the header() if it exists else I proceed to the dashboard.

if (isset($_GET['next'])) {
    $location_redirect = $_GET['next'];
} else {
    $location_redirect = "member/dashboard";
}
header("location: $location_redirect");
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement