phpoutput-bufferingob-start

Can I use ob_clean() without ob_start() before?


I am not used to ob_* functions and I began by reading the documentation.
I would like to use ob_clean() in a method but the documentation says:

The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_CLEANABLE flag. Otherwise ob_clean() will not work.

However I tried (just to see how it "wouldn't work"):

echo 'a';
ob_clean();
echo 'b';

Which outputs b. Everything seems working fine here, but following the documentation, it shouldn't, should it ?


Solution

  • The short answer is that yes, you have to turn on output buffering before you can use ob_clean. However, it is possible that you have output buffering enabled for all files through the output_buffering ini parameter (see the manual). The way to check for this is through ob_get_level():

    echo ob_get_level();
    

    If the result is non-zero, output buffering is enabled.

    If you do use ob_clean() without buffering enabled, you should see an error similar to this:

    Notice: ob_clean() [ref.outcontrol]: failed to delete buffer. No buffer to delete. in [file-path]