2012-08-06 241 views
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是真的,我得到這個:如何使用ob_start在PHP中的標題位置重定向?

<body>Hello 

我想是時候$condition將是真的,那麼去谷歌!

我不知道發生了什麼,你能解釋還是給我一個解決方案!?

謝謝。

+0

IMO,ob_start()可以用 – asprin 2012-08-06 05:57:23

+0

免掉我可以」 t刪除ob_start(),因爲我需要在寫入客戶端之前處理輸出。 – 2012-08-06 06:00:10

回答

4

只需在標題調用之前添加ob_end_clean();

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 

} 
2

一切都應該工作,只要把;回聲 「<body><p>Hello」 後,你會被罰款..