2014-07-09 130 views
0

現在如果我加載使用GET變量onetwo會重定向的頁面,但它之前它會顯示這個PHP錯誤:Warning: Cannot modify header information - headers already sent by (output started at /home/site/public_html/lp-19.php:3) in /home/site/public_html/lp-19.php on line 5頭已經發出已

繼承人我的代碼:

<?php if(isset($_GET['one']) && isset($_GET['two'])) {?> 

<?php 
$value = "none"; 
setcookie("Disagree", $value, time()+30); 
?> 


<!DOCTYPE html> 
<html> 
<head> 
<script type='text/javascript' src='//redirect.com/script.js'></script> 
</head> 
<body> 
set "Disagree" cookie and then redirect 
</body> 
</html> 

<?php } else { ?> 

<?php 
$value = "agree"; 
setcookie("Yes", $value, time()+3000000); 
?> 

<!DOCTYPE html> 
<html> 
set "yes" cookie and display content if no "one" or "two" get variables in url 
</html> 
<?php }?> 

我該如何擺脫這個錯誤,並根據哪個頁面被加載來讓php設置一個cookie?

回答

0

試試這個;)

<?php 
$has_value = isset($_GET['one']) && isset($_GET['two']); 

if(!$has_value) { 
    $value = "agree"; 
    setcookie("Yes", $value, time() + 3000000); 
} 

if($has_value) { 
    $value = "none"; 
    setcookie("Disagree", $value, time() + 30); 
    ?> 
    <!DOCTYPE html> 
    <html> 
    <head> 
     <script type='text/javascript' src='//redirect.com/script.js'></script> 
    </head> 
    <body> 
    set "Disagree" cookie and then redirect 
    </body> 
    </html> 

<?php 
} 
else { 
    ?> 

    <!DOCTYPE html> 
    <html> 
    set "yes" cookie and display content if no "one" or "two" get variables in url 
    </html> 
<?php } 
1

的問題是因爲Cookie是在性反應的頭,它必須在性反應的身體之前發送給瀏覽器發送。輸出任何東西都進入響應主體。

您可以通過多種方式解決這個問題,其中包括輸出緩衝,或者乾脆運行的所有的邏輯之前將輸出頭的輸出代碼,但在這裏,似乎你只輸出數據做了JavaScript重定向。

不要負荷的JavaScript只是重定向,設置在PHP重定向頭,它也簡化了你的代碼:

<?php 
if(isset($_GET['one']) && isset($_GET['two'])) { 
    $value = "none"; 
    setcookie("Disagree", $value, time()+30); 
    header('Location: redirectUrlHere'); //<-set the correct url 
    die(); 
} 
$value = "agree"; 
setcookie("Yes", $value, time()+3000000); 
?> 

<!DOCTYPE html> 
<html> 
    ... 
</html> 

編輯按您的評論:

<?php 
if(isset($_GET['one']) && isset($_GET['two'])) { 
    $value = "none"; 
    setcookie("Disagree", $value, time()+30); 
}else{ 
    $value = "agree"; 
    setcookie("Yes", $value, time()+3000000); 
} 

if($value=="none"):?> 
    <!DOCTYPE html> 
    <html> 
     <head> 
      <script type='text/javascript' src='//redirect.com/script.js'></script> 
     </head> 
     <body></body> 
    </html> 
<?php else:?> 
    <!DOCTYPE html> 
    <html> 
     ... 
    </html> 
<?php endif;?> 
+0

這看起來很乾淨,但我需要JavaScript重定向而不是PHP ..我將如何使用該代碼?這會花費時間在重定向之前加載html標籤之間的內容,還是首先重定向? –

+0

@JoeBobby這將立即重定向 - 爲什麼你需要JavaScript重定向? – Steve

+0

因爲它的外部腳本多數民衆贊成從儀表板 –