现在,如果我使用获取变量one
和two
加载页面,它将重定向,但它会显示此错误: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 :(得分: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;?>
答案 1 :(得分: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 }