How to implement the returnurl like SO in PHP?

…衆ロ難τιáo~ 提交于 2019-12-02 10:30:24

If you are trying to create a login system with redirection you need to use the HTTP_REFERER header to find out where the user came from so you can send him back there. The best way to do this is, in your login form use something like this:

//- Login.php
<?php
    if ($_POST['username'] && $_POST['password'])
    {
        //- Run username and password verifying script
        header("Location: ".$_POST['returnurl']);
    }
    $RedirectURL = $_SERVER['HTTP_REFERER'];
?>
<form action="/login.php" method="post">
    <input type="text" name="username" />
    <input type="password" name="password" />
    <input type="hidden" name="returnurl" value="<?php echo $RedirectURL; ?>" />
</form>

Please note that some ISPs, browsers or proxies will strip out the referer header, so you can't rely on it to work perfectly for every user. If you use an if statement to check whether the header exists or not, you can send those users back to the homepage or whatever.

EDIT

If you're looking to use $_SERVER['REQUEST_URI'] it should be set to the pretty URL after a rewrite if you're running Apache. If you're running IIS, in which case you need to check for $_SERVER['X_HTTP_ORIGINAL_URL']. Something like this:

<?php
    if (!isset($_SERVER['X_HTTP_ORIGINAL_URL']))
        $ReturnURL = $_SERVER['X_HTTP_ORIGINAL_URL'];
    else
        $ReturnURL = $_SERVER['REQUEST_URI'];

    header("Location: /login.php?returnurl=".$ReturnURL);
?>

and

//- Login.php
<?php
    if ($_POST['username'] && $_POST['password'])
    {
        //- Run username and password verifying script
        header("Location: ".$_POST['returnurl']);
    }
    $RedirectURL = isset($_GET['returnurl'] ? $_GET['returnurl'] : "/index.php";
?>
<form action="/login.php" method="post">
    <input type="text" name="username" />
    <input type="password" name="password" />
    <input type="hidden" name="returnurl" value="<?php echo $RedirectURL; ?>" />
</form>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!