5

Is there a smart way to check whether output has already been sent to the browser and sending a header would generate a PHP_WARNING?

Obviously there's the alternative of using an output buffer, but that's not always an option.

bignose
  • 30,281
  • 14
  • 77
  • 110
Alan Plum
  • 10,814
  • 4
  • 40
  • 57

3 Answers3

6

You can use the headers_sent() method. This because before anything is outputted, the headers will be send first.

Peter Smit
  • 27,696
  • 33
  • 111
  • 170
2

headers_sent() does a poor job and doesn't always return TRUE in case the output has been sent (e.g. notices and warnings).

As an alternative, I use this:

<?php

$obStatus = ob_get_status();

if ($obStatus['buffer_used'] > 0) {
    echo 'Content was sent';
} else {
    echo 'Content was NOT sent';
}
Binar Web
  • 867
  • 1
  • 11
  • 26
-1

If all you want is to hide the warning, just turn off error reporting:

$old_er = error_reporting(0);

header(...)

error_reporting($old_er);

Or, you can redirect PHP errors and warnings to a log file (which is preferable in production, IMO).

strager
  • 88,763
  • 26
  • 134
  • 176