Prevent output buffering with PHP and Apache

brianmearns picture brianmearns · Feb 22, 2013 · Viewed 14.8k times · Source

I have a PHP script which sends a large number of records, and I want to flush each record as soon as it is available: the client is able to process each record as it arrives, it does not need to wait for the entire response. I realize it takes slightly longer for the entire transfer because it needs to be sent in multiple packets, but it still allows the client to start working sooner.

I've tried all the different flush() and ob_flush() functions but nothing seems to help get the data actually sent over the line before the page is finished. I've confirmed that it is not the web browser because I've tested it using telnet.

Answer

brianmearns picture brianmearns · Feb 22, 2013

The only solution that worked for me was to set the output_buffering directive in php.ini to "Off". I didn't want to do this for the entire server, just this one specific resource. Normally you could use ini_set from the PHP script, but for whatever reason php doesn't allow output_buffering to be set in this way (see the php manual).

Well it turns out that if you're using Apache, you can set some php ini directives (including output_buffering) from your server config, including a .htaccess file. So I used the following in a .htaccess file to disable the output_buffering just for that one file:

<Files "q.php">
    php_value output_buffering Off
</Files>

And then in my static server configuration, I just needed AllowOverride Options=php_value (or a larger hammer, like AllowOverride All) in order for that to be allowed in a .htaccess file.