What is PHP ob_start() Function?
PHP ob_start() function turns on output buffering. Let’s discuss detail.
As an interpreted language, PHP executes each statement of your code at a time and sends it as output to the browser. This makes the execution process slow. To get rid from this (and from other reasons), PHP allows you to use the output buffering technique that can store the data to the buffer (memory) and then allow you to send it at once to the out.
By default, output buffering is on. You can find it in your php.ini file where output buffering and by default its value is 4096 bytes (or 4 KB). So, after running a PHP script, the first 4096 bytes of content get buffered and once this limit exceeds, PHP automatically sends the content to the browser.
While the buffer is on, if you declare ob_start() function, a new layer of buffer adds.
Syntax
ob_start(callback, chunk_size, flags)
Parameters:
There are three parameters in this function-
callback (Optional): This function takes the content of the buffer and after modifying it, it returns the content as a string that is to be flushed out later. This parameter has two parameters-
- buffer – This is the content of the buffer.
- phase – It is a bitmask that may take the following constants-
- PHP_OUTPUT_HANDLER_START – Indicates that output buffering has begun.
- PHP_OUTPUT_HANDLER_FLUSH – Indicates that the output buffer has been flushed, and data to e sent to output.
- PHP_OUTPUT_HANDLER_FINAL – Indicates that this is the final output buffering operation and will be destroyed immediately after.
- chunk_size (optional): It indicates buffer size which will be flushed automatically when it is filled with content. Default value is 0.
- flags (optional): It is a bitmask that controls which operations can be performed on the output buffer. You can use the following four flags. Each flag allows to the following set of functions-
| Flgs | Functions |
| PHP_OUTPUT_HANDLER_CLEANABLE | ob_clean(), ob_end_clean(), and ob_get_clean(). |
| PHP_OUTPUT_HANDLER_FLUSHABLE | ob_end_flush(), ob_flush(), and ob_get_flush(). |
| PHP_OUTPUT_HANDLER_REMOVABLE | ob_end_clean(), ob_end_flush(), and ob_get_flush(). |
| PHP_OUTPUT_HANDLER_STDFLAG or PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_FLUSHABLE | PHP_OUTPUT_HANDLER_REMOVABLE | All the functions of the above 3 flags. |
Return Values:
It returns the following two values –
- TRUE on success
- FALSE on failure.
Examples:
<?php
ob_start();
echo str_pad("First line. More coming after 2 seconds...<br />",4096);
ob_flush();
flush();
sleep(2);
echo "Last line.";
?>
Output:
First line. More coming after 2 seconds... Last line.
PHP Version Support:
PHP 4, PHP 5, PHP 7, PHP 8
Summary: PHP ob_start() Function
The ob_start() is a built-in PHP array function and developers use this function to control the output.