Skip to content

PHP ob_flush() Function: Everything You Need to Know

As a PHP developer, you may need to flush the output buffer to send data to the client immediately rather than waiting for the buffer to fill up. The ob_flush() function is a built-in PHP function that flushes the current output buffer. In this article, we will take an in-depth look at the ob_flush() function and its usage.

What is the ob_flush() Function?

The ob_flush() function is a PHP built-in function that flushes the current output buffer to the next buffer in the chain. Note that output buffering must first be enabled using ob_start(). Additionally, ob_flush() only clears the PHP buffer; to actually send the data to the client, you must also call the flush() function.

How to Use the ob_flush() Function

Using the ob_flush() function is straightforward. Here is the syntax of the function:

The PHP syntax of ob_flush() Function

php
ob_flush();

Here is an example of how to use the ob_flush() function to flush the output buffer and send data to the client:

How to Use the ob_flush() Function?

php
<?php

ob_start(); // Enable output buffering
echo "This will be buffered";
ob_flush(); // Flush PHP buffer to the next buffer
flush();    // Send data to the client

In this example, we enable output buffering with ob_start(), output a message using echo, and then use ob_flush() followed by flush() to push the message to the client immediately.

Note: Server-side buffering (e.g., in Apache or Nginx) may still delay delivery. To ensure immediate delivery, you may need to adjust server configuration or use ob_implicit_flush(true). For complete buffer lifecycle management, you can also use ob_end_flush() or ob_get_clean() when you no longer need buffering.

Conclusion

The ob_flush() function is a useful tool for managing output buffers in your PHP web application. By understanding that it works alongside ob_start() and flush(), you can effectively send data to the client immediately rather than waiting for the buffer to fill up. We hope this article has been informative and useful in understanding the ob_flush() function in PHP.

Practice

What does the ob_flush() function in PHP do?

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.