Question

This code:

ob_start();
ob_end_flush();

header('foo');

Throws warning

Warning: Cannot modify header information - headers already sent

while this:

echo '';
header('foo');

doesn't.

I don't see any significant difference between them.

So is this behaviour expected or not?

PS: php 5.3.2

Was it helpful?

Solution

My initial reaction to this was "that's the behaviour I would expect" but it turns out there are some subtleties hinging on the PHP version you are using.

First let's cover why my initial reaction was what it was, since (given that you are using 5.3) it does apply to your tests:

ob_end_flush() implicitly calls flush(), pushing the headers to browser regardless of whether any content has been generated.
echo ''; on the other hand is basically a NOOP - you asked the engine to do nothing, so nothing happens.

However, a little more investigation shows that the implicit_flush option for OB is in fact off by default, so this shouldn't in fact make any difference unless you have enabled the option explicitly.

Moreover, this behaviour is not seen before 5.2.2 or from 5.4.0+ - so my next port of call was to compare this with this. Even if you can't read C at all, it should be plainly obvious that there is a huge difference between the output handling in 5.3 and 5.4 - a fairly substantial rewrite has happened.

Due to real-life commitments I have yet to pull it apart properly and find the relevant key code for this specific issue, but I will do so soon and expand on this answer when I have done so.


Summary:

  • Depending on your PHP version and configuration, this may quite possibly be logical and expected behaviour.
  • Heavy differences in PHP versions make this question have more that just one simple answer
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top