tags:

views:

129

answers:

2

I have an import that needs to notify the user each time an item has been successfully imported into the database. Is there a way to loop, perform some functionality, provide the output message, and then loop through again with the same action?

+6  A: 

You can use the flush() function to send output to the user before the PHP script has finished.

flush — Flush the output buffer

Flushes the output buffers of PHP and whatever backend PHP is using (CGI, a web server, etc). This effectively tries to push all the output so far to the user's browser.

flush() has no effect on the buffering scheme of your web server or the browser on the client side. Thus you need to call both ob_flush() and flush() to flush the output buffers.

Several servers, especially on Win32, will still buffer the output from your script until it terminates before transmitting the results to the browser.

Server modules for Apache like mod_gzip may do buffering of their own that will cause flush() to not result in data being sent immediately to the client.

Even the browser may buffer its input before displaying it. Netscape, for example, buffers text until it receives an end-of-line or the beginning of a tag, and it won't render tables until the </table> tag of the outermost table is seen.

Some versions of Microsoft Internet Explorer will only start to display the page after they have received 256 bytes of output, so you may need to send extra whitespace before flushing to get those browsers to display the page.

This would be used after you display a message or whatever.

echo "Patience";

while (!done)
{
    echo ".";
    flush();
}
John Kugelman
N.B.: What you should take away from the caveats on the `flush()` function is that while it (esp. in combination with `ob_flush()`) gives you the *best chance* of success, there's simply no way to *guarantee* that visitors will see anything before your script terminates.
Ben Blank
A: 

Not an exact duplicate, but related to http://stackoverflow.com/questions/951556/how-can-you-push-data-to-a-web-page-client/951785#951785

cdonner
Question wasn't if or not it was possible or a good idea, but rather how to do it.
Ian Elliott
The question that I referenced was also about how to do it, and there were answers there (no in my response, but I did not imply that). The difference is in timing. This other discussion was about long-running connections, like in a chat client, where you need to send data asynchonously to the client over a long period of time. Flushing the response buffer would not be an appropriate solution. The question here was not specific enough to make that call.
cdonner