2
<?php

ob_start();

echo "<body><p>Hello "

if ($condition) {
   header( "Location: http://www.google.com/" );
   exit;
}

echo " World!</p></body>";
ob_end_flush();

?>

什么时候$condition是真的我明白了:

<body>Hello

我想要的是什么时候$condition是真的然后去谷歌!

我不知道发生了什么,你能解释一下或给我一个解决方案吗!?

谢谢。

4

4 回答 4

2

一切都应该工作,只需;在 echo " <body><p>Hello" 之后添加一个,你会没事的..

于 2012-08-06T09:14:14.200 回答
2

只需ob_end_clean();在标题调用之前添加。

于 2012-08-06T05:58:19.590 回答
1

如果我是你,我会先开始可能出错的地方,然后再进行处理。

一个例子

$exit_condition_1 = some_value1;
$exit_condition_2 = some_value2;

if($exit_condition_1 == false){

     //Redirect
     //Exit

}

if(!$exit_condition_2){

     //Redirect
     //Exit

}


//start the buffer ob_start()

//show some HTML

//flash the buffer ob_end_clean()

there is no point of starting the buffer then if something goes wrong close it and redirect. Just do value testing at the begining then process the request.

An example: lets say that you want to view a product's info and you have a function that will do that


function view_product($product_id){

   if(!$product = getProductById($product_id)){

        //product does not exist, redirect
   }


   if(the user does not have enough access rights){

     //show a message maybe 
     //redirect
   }


   //everything is alright then show the product info

}
于 2012-08-06T06:02:24.357 回答
0

为了解决一个函数使用 ob_start() 并且header("Location: http://www.example.com");之后出现但错误“已经发送... ”的类似情况,我将header(...调用替换为

echo "<script> window.location.href = 'https://www.example.com' </script>"

它在这种特殊情况下有效(无论如何,只需要一个页面重定向)。

于 2020-02-07T15:08:18.573 回答