已发送的标头处理遗留代码


Headers already sent dealing with legacy code

这个问题我已经发布了一千次,但我没有看到的是以下情况的答案。也许已经存在一个?

我已经确定了一些事情:

  • <?php?>周围没有空间。
  • 没有回声语句。
  • 没有打印语句或任何其他"输出数据语句">

有一个问题:

有问题的代码被"包含在导致问题的"布局页面"中,也许有人可以告诉我如何解决这个问题?

所以这是代码,我没有写这个,我只是在维护它。

$pagetitle = $_SERVER['REQUEST_URI'];
switch ($pagetitle) {
  ...
  case "/locations.php?l=8" :
    echo '<title>Mississauga West, Canada Winemaking - Vinbon</title>';
  break;
  ...
}

在这种情况下,我尝试执行以下操作,知道由于 echo 语句,它可能不起作用。

case "/locations.php?l=8" :
  ob_start();
  header("HTTP/1.1 301 Moved Permanently");
  header("Location: http://www.New-Website.com");
  die();
  ob_end_flush();
break;

现在我知道你们已经在一些答案中表示不要在上面设置回声,因为这可能会导致问题。我想ob_start()会澄清这一点吗?

如您所见,这一定是 301 重定向。

现在这段代码位于一个名为:inc_meta.php的文件中,该文件随后包含在(不是必需的(名为layer01.php的文件中。

运行时,它会导致以下"警告":

Warning: Cannot modify header information - headers already sent by (output started at /home/content/46/11552446/html/layout/layer01.php:5) in /home/content/46/11552446/html/layout/layer01.php on line 10
Warning: Cannot modify header information - headers already sent by (output started at /home/content/46/11552446/html/layout/layer01.php:5) in /home/content/46/11552446/html/layout/layer01.php on line 11

现在第 5 行是我们做<? include inc_meta.php ?>的地方,layer01.php 只不过是一个 html 文件。

第 10 行是 <body> 标记上方的空格,第 11 行是<body>标记。

我不能使用 javascript,因为这必须是此位置的 301 重定向。有人有什么想法吗?

更新 1

所以我尝试删除 echo 语句,因为我认为你们会说这是问题所在

我现在得到:

Warning: Cannot modify header information - headers already sent by (output started at /home/content/46/11552446/html/layout/layer01.php:5) in /home/content/46/11552446/html/layout/inc_meta.php on line 51
Warning: Cannot modify header information - headers already sent by (output started at /home/content/46/11552446/html/layout/layer01.php:5) in /home/content/46/11552446/html/layout/inc_meta.php on line 52

第 51 行和第 52 行是指:

header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.New-Website.com");
问题是在

php/html 文件中,我不知道您必须将此文件包含在 <DOCTYPE ... ><html> 标签上方。一旦它被包含在那里,问题就解决了它自己。

所以就我而言:

<? include('inc_meta.php'); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
....

而不是它是什么:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<? include('inc_meta.php'); ?>
...