1

可能重复:
PHP 错误:无法修改标头信息 - 标头已发送 标头
已由 PHP 发送

这是我的代码:

<html>
<body>
    <?php

    if($country_code == 'US')
    {
        header('Location: http://www.test.com');
    }

    else 
    {
        header('Location: http://www.test.com/');
    }

    ?>

<script language="JavaScript" type="text/javascript"></script>

</body>
</html>

<?php前后没有空格?>

我曾尝试将 HTML 代码和 Javascript 完全放在 PHP 之下,但这会使其无法跟踪对页面的点击。

4

4 回答 4

4

在您的标题之前不应输出任何内容。标头总是在内容之前发送。在调用 之前,您不能输出任何内容header(),并期望它能够正常工作。(一些服务器可以启用输出缓冲来解决这个问题,但它不能解决任何问题,也不是很好依赖。)

您关于跟踪页面点击的注释是无稽之谈。大多数浏览器在给定带有标题301302状态码时不会费心渲染 HTML 。Location:

于 2012-12-16T23:30:55.330 回答
1

如果您主要担心的是 javascript 跟踪代码,那么我建议您使用 javascript 重定向:

<?php
// pre-html PHP code
?><!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="trackingScript.js"></script>
<script type="text/javascript">
<?php
if($country_code == 'US'){
  echo "document.location.href = 'http://www.test.com/1';";
}else{
  echo "document.location.href = 'http://www.test.com/2';";
}
?>
</script>
</head>
<body></body>
</html>
于 2012-12-16T23:52:05.940 回答
0

您可以将 PHP 代码放在文件的开头。

<?php
if($country_code == 'US')
{
    header('Location: http://www.test.com');
}
else 
{
    header('Location: http://www.test.com/');
}

?>
<html>
<body>

<script language="JavaScript" type="text/javascript"></script>

</body>
</html>
于 2012-12-16T23:59:58.330 回答
0

是的,在输出开始后无法发送标头,这样的事情可以解决它

function redirect_to($url){
    // If the headers have been sent, then we cannot send an additional location header
    // so output a javascript redirect statement.
    if (headers_sent()){
       echo "<script>document.location.href='" . htmlspecialchars($url) . "';</script>\n";
    }else{
       header('HTTP/1.1 303 See other');
       header('Location: ' . $url);
    }
 }

 redirect_to('http://www.test.com/');
于 2012-12-16T23:41:21.160 回答