0

I'm aware of the restriction to functions that modify header information like session_start() and the header() functions that produce the Warnings "Cannot modify header" or "Cannot send session cache limiter" and the reason and solutions, all available here: How to fix "Headers already sent" error in PHP

What I want to know is, why is it that when I get these errors it's not at whitespace before php tags or the START of HTML output? Usually the error occurs somewhere in the middle of a large block of HTML output that happens before any calls to the header functions.

In these cases, prior to receiving the Warnings, the header functions actually work, AFTER raw HTML output. But at some point either something changes or I add something and I start getting the warning, which usually points to a spot after a lot of HTML output.

This makes me think that the HTML I'm outputting is normally being automatically buffered (ob_start() fixes the problem) up to a point, then something causes the output.

My header.php file:

<!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"); ?>

In a separate file:

<?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');

?>

It seems to me that if I was going to get this error, it should occur at the start of header.php at my DOCTYPE tag...but then there's quite a bit of HTML, and the output is noted as starting in main-nav.php.

I'd like to know WHY.

Thanks!

Community
  • 1
  • 1
Hybrid
  • 21
  • 1
  • 1
  • 6

1 Answers1

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

You're getting 'headers already sent' because you've already done output at the time you try to call header(). The header() calls MUST come before ANY output from your code, e.g.

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

would work

Marc B
  • 356,200
  • 43
  • 426
  • 500