PHP page redirect [duplicate]

2019-01-02 20:21发布

This question already has an answer here:

Can PHP make a redirect call after executing a function? I am creating a function on the completion of which I want it to redirect to a file located in the same root folder. Can it be done?

 if {
      //i am using echo here
 }

 else if ($_SESSION['qnum'] > 10) { 
            session_destroy();
            echo "Some error occured.";
            //redirect to user.php
        }

15条回答
高级女魔头
2楼-- · 2019-01-02 20:54

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).

查看更多
有味是清欢
3楼-- · 2019-01-02 20:58
<?php

    http_redirect("relpath", array("name" => "value"), true, HTTP_REDIRECT_PERM);

?>
查看更多
浅入江南
4楼-- · 2019-01-02 21:02
   $url='the/url/you/want/to/go';
   echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';

this works for me fine.

查看更多
只靠听说
5楼-- · 2019-01-02 21:02

if you want to include the redirect in your php file without necessarily having it at the top, you can activate output buffering at the top, then call redirect from anywhere within the page. Example;

 <?php
 ob_start(); //first line
 ... do some work here
 ... do some more
 header("Location: http://www.yourwebsite.com/user.php"); 
 exit();
 ... do some work here
 ... do some more
查看更多
余生无你
6楼-- · 2019-01-02 21:03

actually, I found this in the code of a php based cms.

redirect('?module=blog', 0);

so it is possible. In this case, you are logged in at the admin level, so no harm no foul (I suppose). the first part is the url, and the second? I can't find any documentation for what the integer is for, but I guess it's either time, or data since it is attached to a form.

I, too, wanted to refresh a page after an event, and placing this in a better spot worked out well.

查看更多
还给你的自由
7楼-- · 2019-01-02 21:06
header( "Location: http://www.domain.com/user.php" );

But you can't first do an echo, and then redirect.

查看更多
登录 后发表回答