2

I have a script that has a call to header(); and its working fine for a couple of days since I first started running the script.

then after a couple of days, it started to have an error saying it cannot modify header information.

Then I put ob_start(); and ob_end_flush(); upon googling the error and it works!

The error has gone but my question is that why it works without ob_start(); and ob_end_flush(); for a couple of days before?

I want to know the explanation behind this behavior.

btw, I call header() this way:

if(condition is true){
header('Location: anotherpage.php');
}

and I have a session_start(); at the beginning.

anagnam
  • 457
  • 6
  • 23

3 Answers3

2

Previously, you had no non-header output before the header line. Now, you have non-header output before the header line. That will only work if the output is buffered so the header can be actually output ahead of it.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
1

You can not output any data before a header!

ob_start() is a output buffer and will buffer all echoed data and print it after all headers etc.

PHP flushes the data when the script is finished automatically so there's no need of the "ob_end_flush()"

Niclas Larsson
  • 1,317
  • 8
  • 13
1

You have some code outputting something before header() is called. It can be a print, echo or similiar statement, or even a white space before <?php.

The reason why ob_start causes the error to go away is because it causes any output to be buffered, therefore defered until the moment you call ob_flush.

This way it's guaranteed that the headers will come before content, even if you mess with the order of the commands in the code.

Doug
  • 6,322
  • 3
  • 29
  • 48