简体   繁体   中英

php navigate to previous page after login workaround

So for some reason, I tried http_referer and it isn't working for me...or maybe it is but this is the reason why I'm trying a workaround. I'm testing a login script in my browser and I want the user to go back to the previous page which they were visiting.

The issue I ran into is when I put in my login credentials, Firefox and Chrome pop out a "Save Password" option and I THINK it acts like a page. So when http_referer is called or when

echo '<script type="text/javascript">javascript:history.go(-1);</script>';

The page is still on the login page! Well what if the user clicks once "Don't Save" and that option is saved...then using history.go(-2) wouldn't work. Here's the workaround I tried but I can't get it to work.

Initially if the login info is correct, I call the first history.go(-1). Then I'm using this function to get the current page and if it matches login.php, I want to go back one more page! But it's not working. Please advise me

if($login_check > 0){
    echo '<script type="text/javascript">javascript:history.go(-1);</script>';
    function curPageName() {
        return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
    }
    $curpage = curPageName();
    if ($curpage = "login.php"){
        echo '<script type="text/javascript">javascript:history.go(-1);</script>';
    }
}

I've also read to use sessions but my session array saves data for the shopping cart so I'm not sure how I would use sessions for navigation.

Why not store the URL of the page that redirects to the login page in a session and then redirect to it on a successful login? That way even if the user has a few failed login attempts they'll still get to the right page.

Another benefit for this method over javascript is that the redirect is sent in the header on page request, no need to send the user js.

Save the URL as a session variable when the user is not logged in.

// not logged in
$_SESSION['redirect_url'] = 'http://'.$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
//now redirect to login page, something like
header("Location: http://www.site.com/login");

Nb. The URL above is crudely constructed, if you are using SSL or a different port (not 80) you'll need to change it accordingly.

Retrieve it on successful login

//login successful 
header("Location: ".$_SESSION['redirect_url']);
exit;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM