# Output Buffering

Output buffering is the buffering (temporary storage) of output before it is flushed (sent and discarded) to the browser (in a web context) or to the shell (on the command line). While output buffering is active no output is sent from the script, instead the output is stored in an internal buffer.

## Buffering Affecting PHP

PHP relies on the underlying software/hardware infrastructure when flushing output. Buffering implemented by consoles on the command line (e.g. line buffered) or web servers and browser in a web context (e.g. fully buffered) do affect when output is displayed to the end-user. Some of these effects can be eliminated by fine-tuning server settings and/or aligning buffer sizes of the various layers.

## Output Buffering Control In PHP

PHP provides a fully buffered user-level output buffer with functions to start, manipulate and turn off the buffer (most ob_* functions), and two functions to flush the underlying system buffers (flush() and ob_implicit_flush()). Some of this functionality can be set and/or configured using the appropriate php.ini settings as well.

## Use Cases

Output buffering is generally useful in situations when the buffered output is modified or inspected, or it is used more than once in a request; or when the controlled flushing of output is desired. Specific use cases include:

- caching the result of compute/time intensive scripts for example by generating static `HTML` pages
- re-using the generated output by displaying it, saving it to a file and/or sending it by email
- flushing the `head` of an `HTML` page separate from the `body` allows browsers to load external resources while the script executes potentially more time consuming processes (e.g. database/file access, external network connection). This is only useful if the `HTTP` status code cannot change after the headers are sent
- extracting information from functions that would otherwise produce output (e.g. phpinfo())
- controlling the output of third-party code by modifying/using parts (e.g. extracting data, replacing words/phrases, adding missing `HTML` tags), or discarding it entirely under certain conditions (e.g. errors)
- polyfilling certain unavailable web server functionality (e.g. compressing or encoding output)

`↑` and `↓` to navigate • `Enter` to select • `Esc` to close • `/` to open