What is output buffering in PHP?
✔ Recommended Answer
Output Buffering for Web Developers, a Beginner’s Guide:
Without output buffering (the default), your HTML is sent to the browser in pieces as PHP processes through your script. With output buffering, your HTML is stored in a variable and sent to the browser as one piece at the end of your script.
Advantages of output buffering for Web developers
- Turning on output buffering alone decreases the amount of time it takes to download and render our HTML because it's not being sent to the browser in pieces as PHP processes the HTML.
- All the fancy stuff we can do with PHP strings, we can now do with our whole HTML page as one variable.
- If you've ever encountered the message "Warning: Cannot modify header information - headers already sent by (output)" while setting cookies, you'll be happy to know that output buffering is your answer.
Source: stackoverflow.com
Answered By: ax.
Output buffering in PHP is a mechanism that allows the output generated by a PHP script to be stored in a buffer before it is sent to the browser or client. Instead of immediately sending the output to the browser, the output buffer captures the output and holds it until the buffer is flushed or cleared.
Output buffering can be enabled in PHP by using the ob_start()
function at the beginning of a script. This function starts output buffering and any output generated by the script is stored in the buffer until it is flushed.
Output buffering is useful in several scenarios such as:
Improving performance: By capturing all the output generated by a script and sending it at once, output buffering can reduce the number of HTTP requests made to the server, thereby improving performance.
Conditional output: Output buffering allows you to conditionally display output generated by a script, such as displaying an error message only if a certain condition is met.
Manipulating output: Output buffering can also be used to manipulate the output generated by a script, such as adding headers or footers to the output, or modifying the content of the output before it is sent to the client.
To stop output buffering and send the captured output to the client, you can use the ob_flush()
or flush()
function to send the output to the client and clear the output buffer. You can also use the ob_end_flush()
or ob_end_clean()
function to send or discard the captured output respectively, and stop output buffering.
Comments
Post a Comment