2012-12-16 63 views
1

可能重複發送標題:
PHP error: Cannot modify header information – headers already sent
Headers already sent by PHPPHP不能更改頭信息 - 已經

這是我的代碼:

<html> 
<body> 
    <?php 

    if($country_code == 'US') 
    { 
     header('Location: http://www.test.com'); 
    } 

    else 
    { 
     header('Location: http://www.test.com/'); 
    } 

    ?> 

<script language="JavaScript" type="text/javascript"></script> 

</body> 
</html> 

沒有空間之前<?php或af ter ?>

我已經嘗試將HTML代碼和Javascript放在PHP下面,但是這樣會使它無法跟蹤點擊頁面。

+1

你已經發送''... – Dan

+0

它是一個.html文件或PHP文件。如果它是一個html頁面,瀏覽器不能知道php。您的源代碼必須在.php文件中執行php行。 – hakiko

回答

3

在標題之前不應輸出任何內容。標題總是在內容之前發送。在致電header()之前,您無法輸出任何內容,並期望其正常工作。 (有些服務器可以啓用輸出緩衝,可以解決問題,但它不能解決任何問題,並且不太可靠。)

關於跟蹤點擊到頁面的提示是無稽之談。當給定301302狀態碼和Location:標頭時,大多數瀏覽器不會打擾呈現HTML。

+0

這是怎麼回事?我使用的是跟蹤程序,Javascript是它用於跟蹤點擊次數的代碼,並且它的工作方式很順利,只是將它與PHP結合起來存在問題。 – user1887109

+0

這是無稽之談,因爲服務器在向客戶端瀏覽器發送任何內容之前處理php代碼。所以不要把'header()'信息寫入你的HTML-header。 – wildhaber

+1

您需要了解HTTP如何工作的基礎知識。標題在文檔內容之前發送。在頁面中間調用一個'header()'調用不會改變頭部實際出現的位置。您**必須**在內容前發送標題。再一次,我不知道你運行的是什麼JavaScript,但是大多數瀏覽器不會因爲HTML被重定向而煩惱,並且JavaScript不會運行。如果任何內容使用「3xx」狀態碼發送,則應該只是一條友好的消息,指示用戶被重定向到的位置。 – Brad

0

是頭不能輸出開始後發送,這樣的事情可以解決它

function redirect_to($url){ 
    // If the headers have been sent, then we cannot send an additional location header 
    // so output a javascript redirect statement. 
    if (headers_sent()){ 
     echo "<script>document.location.href='" . htmlspecialchars($url) . "';</script>\n"; 
    }else{ 
     header('HTTP/1.1 303 See other'); 
     header('Location: ' . $url); 
    } 
} 

redirect_to('http://www.test.com/'); 
1

如果你的主要煩惱是JavaScript跟蹤代碼,那麼我會建議一個JavaScript重定向:

<?php 
// pre-html PHP code 
?><!DOCTYPE html> 
<html> 
<head> 
<script type="text/javascript" src="trackingScript.js"></script> 
<script type="text/javascript"> 
<?php 
if($country_code == 'US'){ 
    echo "document.location.href = 'http://www.test.com/1';"; 
}else{ 
    echo "document.location.href = 'http://www.test.com/2';"; 
} 
?> 
</script> 
</head> 
<body></body> 
</html> 
0

您可以將PHP代碼放在文件的開始位置。

<?php 
if($country_code == 'US') 
{ 
    header('Location: http://www.test.com'); 
} 
else 
{ 
    header('Location: http://www.test.com/'); 
} 

?> 
<html> 
<body> 

<script language="JavaScript" type="text/javascript"></script> 

</body> 
</html> 
相關問題