2012-04-10 81 views
0

這是我第一次在這個網站上提問,所以請耐心等待。我從另一個網站獲得了用於測試互聯網連接速度的腳本,並添加了其他語句。如果速度超過500,它將重定向到特定頁面。出於某些原因,我無法使其工作。我在<html>標記之前添加了ob_start();,並在</html>標記之後添加了ob_end_flush();。我在下面的代碼中加入了我的body標籤。我的PHP如果語句不起作用

$kb=512; 
flush(); 
$time = explode(" ",microtime()); 
$start = $time[0] + $time[1]; 

for($x=0;$x<$kb;$x++){ 
    echo str_pad('', 1024, ''); 
    flush(); 
} 
$time = explode(" ",microtime()); 
$finish = $time[0] + $time[1]; 
$deltat = $finish - $start; 
$intspeed = round($kb/$deltat, 0); 
echo $intspeed; //just to check if $intspeed has a value 

if ($intspeed > 500) { 
    header("Location: test.php"); 
    exit(); 
} else { 
    header('Location: falcons/index.php'); 
    exit(); 
} 
+3

在發送自定義標題之前,您無法在屏幕上打印任何內容(使用'echo')。您在屏幕上回顯某些內容,然後發送重定向標頭。那就是問題所在。刪除回聲。 – 2012-04-10 17:33:44

+1

幽默地說,'echo $ intspeed'會阻止重定向 – 2012-04-10 17:34:19

+0

我非常確定輸出緩衝會繞過這個......當然,只有當代碼位於ob_start()和ob_end_flush()之間時,OP說,他使用,而不是之前或之後。 – MichaelRushton 2012-04-10 17:34:55

回答

1

刪除flush();來電。此外,請確保此代碼位於ob_start()ob_end_flush()之間,而不是之前或之後(並且在此代碼之前沒有其他輸出)。

$kb=512; 

$time = explode(" ",microtime()); 
$start = $time[0] + $time[1]; 

for($x=0;$x<$kb;$x++){ 
    echo str_pad('', 1024, ''); 
} 
$time = explode(" ",microtime()); 
$finish = $time[0] + $time[1]; 
$deltat = $finish - $start; 
$intspeed = round($kb/$deltat, 0); 
echo $intspeed; //just to check if $intspeed has a value 

if ($intspeed > 500) { 
    header("Location: test.php"); 
    exit(); 
} else { 
    header('Location: falcons/index.php'); 
    exit(); 
} 
0

您只能通過重定向頭()如果輸出尚未開始。如果已經有非標題輸出(如在for循環中),設置「Location」標題不起作用。

我建議在設置「位置」標頭之前使用headers_sent(),並在出現一些調試信息或其他已經開始輸出的情況下進行回退。

+0

謝謝。它現在有效!我必須刪除回顯和flush()。 – Filap 2012-04-10 18:09:31