skip to Main Content

The code snippet is:

ob_start();
echo 'ok';
ob_get_contents();
exit; 

Expected result: should print nothing.
Actual result: for some reason ok has printed

2

Answers


  1. The manual page about output buffers explains:

    Every output buffer that has not been closed by the end of the script or when exit() is called will be flushed and turned off by PHP’s shutdown process.

    Since you only retrieved the content of the buffer, but did not "clean" it with ob_clean(), ob_end_clean() or ob_get_clean(), the content is still in the buffer when your page finishes, and is flushed to output.

    Login or Signup to reply.
  2. The reason why your code prints "ok" instead of nothing is because the output buffer is flushed and turned off by PHP’s shutdown process when exit() is called. To prevent this, you can use ob_end_clean() to clean the buffer before calling exit().

    The following code will explain the concept better.

    <?php
    ob_start(); // Start output buffering
    echo "This will be output"; // Output some content to the buffer
    
    // Retrieve the buffer content
    $bufferContent = ob_get_contents();
    
    // Option 1: Clean the buffer and continue script execution
    ob_clean();
    echo "Buffer cleaned, this will be output"; // This will be output
    
    // Option 2: End and clean the buffer without outputting its content
    ob_end_clean();
    exit(); // Terminate script, no content will be output
    
    // Option 3: Flush and turn off the output buffer, sending its content
    ob_end_flush();
    exit(); // "This will be output" will be printed
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search