PHP Tip using flush()

You may have noticed that scripts which take a long time to execute often display nothing but a blank “loading” page in the web browser until they finish running. If you find yourself in this situation with a script you’ve written, it’s possible to make the script output incrementally. To do this, use the flush() command. flush() will force the script to send any data in the output buffer to the browser immediately, instead of waiting until execution terminates.

For example, suppose you have a newsletter with several thousand subscribers and because each message contains a unique unsubscription link, the mails must be sent to one recipient at a time. Unfortunately, your script takes upwards of 10 minutes to run, and you’re never sure how far along it is until the entire thing finishes. This can be solved by adding flush() into the loop, to print out a realtime status message after every 100 emails:

<?
$result = mysql_query(‘SELECT DISTINCT email FROM newsletter_subscribers’, $db);
while($myrow = mysql_fetch_array($result)){
$body = ” … body plus unsubscription link would go here … “;
mail($myrow[email], ‘This Month’s Newsletter’, $body, ‘From: newsletter@example.com’);
if($tick % 100 == 0){
echo “$tick messages have been sent…<br>”;
flush();
}
}
?>

Once you use flush() a few times, you’ll start finding more and more places where it comes in handy!

Comments are closed.