0

Possible Duplicate:
“Warning: Headers already sent” in PHP

During testing I ran into the "headers already sent" issue. But then I thought, how can this occur? One of the headers is Content-Length which is unknown until the entire PHP script is finished, how does it get around this issue?

Community
  • 1
  • 1
Elliot Chance
  • 5,526
  • 10
  • 49
  • 80
  • http://stackoverflow.com/questions/8028957/warning-headers-already-sent-in-php – Matt Lo Nov 22 '12 at 23:25
  • 2
    @MattLo Not a duplicate; OP understands why the warning is shown, but wants to know how to resolve writing contents first and then sending the `Content-Length` header. Voting to reopen. – Ja͢ck Nov 23 '12 at 15:17

3 Answers3

1

You get this message when you output anything before setting the headers using header(). So, make sure you don't echo anything, there's no HTML, no whitespace... nothing at all before you set the header.

sachleen
  • 30,730
  • 8
  • 78
  • 73
1

You should use output buffering:

ob_start();
// write all your code here

header('Content-Length: ' . ob_get_length());

Output buffering gets flushed implicitly when reaching the end of your script

One thing you could try, I'm not sure about, is to leave off the header() call and see if PHP automatically sets the Content-Length for you.

See also: ob_start()

Edit

If you're talking about how PHP does it, it doesn't always write that header; once the output buffer is full it will flush it without setting an explicit length header.

See also: http://php.net/manual/en/outcontrol.configuration.php

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
0

You have to send the headers before you send anything else to output.Once the script produces anything - be it a static part of the page or a dynamically generated output - PHP sends the headers followed by whatever was sent to output (unles you use buffering, mentioned in other answers).

Hence you have to start your file with <?php and make sure, that it doesn't contain even the BOM character some editors like to put at before the file contents proper.

peterph
  • 980
  • 6
  • 11