The PHP Language is an interpreted language, i.e. it is executed statement after statement. By default one characteristic of PHP makes it send HTML as chunks as soon as it is generated by executing the statements; this characteristic makes the loading of the webpage granular and the loading time span may appear in a haphazard manner. An Example of the following can be the loading time of a website that prevents adblocker or other similar applications, where the content loads first and then it shows the notification that says to disable the adblocker to see the content.
This is where Output Buffering comes into play. With using output buffering the generated HTML gets stored in a buffer or variable and is sent to the buffer to render after the execution of the last statement in the PHP script. This is a significant increase in performance as well as adds aesthetic value to the webpage. Following are few advantages of using Output Buffering:
Advantages of Output Buffering
- Enabling output buffering, the developer decreases the number of interactions between server and client browser as the whole HTML is sent at once, thus for bigger projects the output buffering provides a much more time efficient approach.
- As the output buffer stores the whole HTML as a string, we can manipulate the HTML with all the string methods or custom methods thus providing a much more flexibility in the rendering the content.
- We can also apply various compression methods thus creating a much more efficient render.
- Setting cookies and working with sessions gets easier using Output buffering as the header information is sent without the rest of the content of the page.
Important points to note
- Being a moderately advanced topic, the output buffering is not enabled by default.
- Output Buffering is able to provide a faster, more secure, more flexible, less redundant approach to render. Output Buffering also allows some advanced functionalities such as minimization, reducing database calls. Output Buffering is apt for cookies and sessions.
- PHP provides an API to enable and access the output buffer. The methods will be discussed in further articles.