2014-07-09 88 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

因为它的外部脚本多数民众赞成从仪表板 –