How to implement the returnurl like SO in PHP?

后端 未结 1 759
渐次进展
渐次进展 2021-01-28 08:07

It should also work after url rewriting.

Is it possible?Otherwise I can only hardcode everything.

相关标签:
1条回答
  • 2021-01-28 08:54

    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>
    
    0 讨论(0)
提交回复
热议问题