header – PHP Blog http://blog.dev-php.site Snippets and guides Tue, 02 Jul 2019 06:45:41 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.4 Redirect after login to the requested page http://blog.dev-php.site/redirect-after-login-to-the-requested-page/ Tue, 02 Jul 2019 06:39:07 +0000 http://blog.dev-php.site/?p=117 Continue reading Redirect after login to the requested page]]> When a user requests a protected page after being logged out (expired session)

// A check on all protected pages that redirects to login. (middleware or include file)
if (!$_SESSION['logged_in']) { // set when a user logs in
    $_SESSION["login_redirect"] = $_SERVER["PHP_SELF"]; // save the page
    header("Location: login.php"); // go to login form
    exit;
}

If login is successful redirect to the intended page if saved in the session or just load the members home page

/* Login is successful */
if ($_SESSION['logged_in']) {
    if (isset($_SESSION["login_redirect"]) {
        header("Location: " . $_SESSION["login_redirect"]);
        unset($_SESSION["login_redirect"]);
    }
    else {
        header("Location: members.php");
        exit();
    }
}
]]>