[英]Headers Already Sent
現在,如果我用get變量one
和two
加載頁面,它將被重定向,但是它在執行此操作之前會顯示此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?
問題是因為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;?>
嘗試這個 ;)
<?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 }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.