为什么不能修改标题信息等引用 html 块的中间


Why does cannot modify header information etc cite the middle of an html block?

我知道对修改标头信息的函数(如 session_start()))和产生警告"无法修改标头"或"无法发送会话缓存限制器"的 header() 函数的限制以及原因和解决方案,所有这些都在这里找到: 如何修复PHP中的"标头已发送"错误

我想知道的是,为什么当我收到这些错误时,它不在 php 标签或 HTML 输出的开头之前的空格处? 通常,错误发生在对标头函数的任何调用之前发生的大块 HTML 输出的中间位置。

在这些情况下,在收到警告之前,标头函数实际上可以工作,在原始 HTML 输出之后。 但是在某些时候,要么某些内容发生了变化,要么我添加了某些内容,然后我开始收到警告,这通常指向大量HTML输出后的一个位置。

这让我认为我输出的 HTML 通常会自动缓冲(ob_start() 修复了问题)到一定程度,然后某些东西会导致输出。

我的头.php文件:

<!DOCTYPE html>
<html lang="en">
<?php
    header("Cache-Control: no-cache, must-revalidate");
    header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
?>    
    <head>
        <!-- style sheets and includes here -->
    </head>
    <?php
    session_start();
    //error_reporting(0);
    // some PHP code here for user checking / cookies
    ?>
    <body>
        <!-- some additional html here -->
    <?php include("resources/main-nav.php"); ?>

在单独的文件中:

<?php
include('pathto/header.php')

//This line works for a while and then stops, producing
// the "Warning: cannot modify headers" line
// The warning that this call produces names a line around 100
// inside the "main-nav.php" file
header('Location: index.php');
?>

在我看来,如果我要收到此错误,它应该发生在标题的开头.php在我的 DOCTYPE 标签上......但是然后有相当多的 HTML,并且输出被标记为从 main-nav.php 开始。

我想知道为什么。

谢谢!

<!DOCTYPE html>         <---this is output
                        <---this is output
<html lang="en">        <---this is output
<?php
    header("Cache-Control: no-cache, must-revalidate");

您得到的是"标头已发送",因为您在尝试调用header()时已经完成了输出。header()调用必须在代码的任何输出之前出现,例如

<?php
    header("Cache-Control: no-cache, must-revalidate");
?>
<!DOCTYPE html>         <---this is output
                        <---this is output
<html lang="en">        <---this is output

会工作