PHP page redirect

This question already has an answer here:

  • How to make a redirect in PHP? 27 answers

  • Yes, you would use the header function.

    header("Location: http://www.yourwebsite.com/user.php"); /* Redirect browser */
    exit();
    

    It is a good practice to call exit() right afterwords so that code below it does not get executed.

    Also, from the documentation:

    Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.

    This means you should not echo anything right before the header() function, as doing so will more than likely throw an error. Also, you will need to verify that this code gets run before any other output as well.


    Using a javascript as a failsafe will ensure the user is redirected (even if the headers have already been sent). Here you go:

    // $url should be an absolute url
    function redirect($url){
        if (headers_sent()){
          die('<script type="text/javascript">window.location=''.$url.'';</script‌​>');
        }else{
          header('Location: ' . $url);
          die();
        }    
    }
    

    If you need to properly handle relative paths, I've written a function for that (but that's outside the scope of the question).


       $url='the/url/you/want/to/go';
       echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';
    

    这对我很好。

    链接地址: http://www.djcxy.com/p/34698.html

    上一篇: 重定向PHP

    下一篇: PHP页面重定向