繁体   English   中英

标头已发送

[英]Headers Already Sent

现在,如果我用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?

问题是因为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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM