使用ob_start时如何在php中重定向头位置?

时间:2012-08-06 05:54:49

标签: php header location ob-start

<?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为真时,请转到Google !!!

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

感谢。

4 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

一切都应该有效,只需在回显“;”后加<body><p>Hello即可,你会没事的。

答案 2 :(得分: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

}

答案 3 :(得分:0)

要解决类似的情况,即函数正在使用ob_start()且此后有header("Location: http://www.example.com");,但出现“ 已发送... ”错误,我替换了{{1} }用

致电
header(...

,并且在特定情况下有效(无论如何,只需重定向页面即可。)