How to flush data to browser but continue executing How to flush data to browser but continue executing php php

How to flush data to browser but continue executing


I have done this in the past and this is how I solved it:

ob_start();/* * Generate your output here */ // Ignore connection-closing by the client/userignore_user_abort(true);// Set your timelimit to a length long enough for your script to run, // but not so long it will bog down your server in case multiple versions run // or this script get's in an endless loop.if (      !ini_get('safe_mode')      && strpos(ini_get('disable_functions'), 'set_time_limit') === FALSE ){    set_time_limit(60);}// Get your output and send it to the client$content = ob_get_contents();         // Get the content of the output bufferob_end_clean();                      // Close current output buffer$len = strlen($content);             // Get the lengthheader('Connection: close');         // Tell the client to close connectionheader("Content-Length: $len");     // Close connection after $len charactersecho $content;                       // Output contentflush();                             // Force php-output-cache to flush to browser.                                     // See caveats below.// Optional: kill all other output bufferingwhile (ob_get_level() > 0) {    ob_end_clean();}

As I said in a couple of comments before, you should watch out for gzipping your content, since that will alter the length of your content, but not change the header about it. It also can buffer your output, so it won't get send to the client instantly.
You could try letting apache know to not gzip your content by using apache_setenv('no-gzip', '1');. But this will not work if you use rewrite-rules to go to your page, since then it will also modify those environment variables. At least, it did so for me.

See more caveats about flushing your content to the user in the manual.


ob_flush writes the buffer. In other words, ob_flush tells PHP to give Apache (or nginx/lighttpd/whatever) the output and then for PHP to forget about it. Once Apache has the output, it does whatever it wants with it. (In other words, after ob_flush it's out of your control whether or not it gets immediately written to the browser).

So, short answer: There's no guaranteed way to do that.

Just a guess, you're likely looking for AJAX. Whenever people are trying to manipulate when page content loads as you're doing, AJAX is almost always the correct path.

If you want to continue a task in the background, you can use ignore_user_abort, as detailed here, however, that is often not the optimal approach. You essentially lose control over that thread, and in my opinion, a web server thread is not where heavy processing belongs.

I would try to extract it out of the web facing stuff. This could mean a cron entry or just spawning a background process from inside of PHP (a process that though started from inside of script execution will not die with the script, and the script will not wait for it to finish before dying).

If you do go that route, it will mean that you can even make some kind of status system if necessary. Then you could monitor the execution and give the user periodic updates on the progress. (Technically you could make a status system with a ignore_user_abort-ed script too, but it doesn't seem as clean to me.)


this is my function

function bg_process($fn, $arr) {    $call = function($fn, $arr){        header('Connection: close');        header('Content-length: '.ob_get_length());        ob_flush();        flush();        call_user_func_array($fn, $arr);        };    register_shutdown_function($call, $fn, $arr);    }

wrap the function to be executed in the end, after php close the connection. and of course the browser will stop buffering.

function test() {    while (true) {        echo 'this text will never seen by user';        }    }

this is how to call the function

bg_process('test'); 

first argument is callable,second argument is an array to be passed to 'test' function with an indexed array

Note : I don't use ob_start() at the beginning of the script.