简体   繁体   中英

PHP Progress Indicator

This is an old problem but there are so many conflicting answers out there that I am asking it again.

I have a PHP script which sends emails to a mailing list of about 200 people. This takes several minutes to do and I would like to display on the screen the name of each recipient as the email is sent, firstly as a check on who is getting the emails and also as a progress indicator. From what I have read, this used to be possible until about ten years ago by flushing the output buffer but, due to 'advances' in the way things are done, this no longer works. Showing progress on a long-running task is a perfectly reasonable thing to want; there must be an answer somewhere. Does anyone know what it is?

Well, your PHP code can run as a CLI standalone application, or it can run as the server-side of a web application or it can run induced by a cron job. Since you want to see a progress bar on the screen, I assume, perhaps wrongly that you are not interested in the cron job / hb task scenario, however, if you do, then the solution would differ only slightly from the webapp scenario.

In the case of CLI, the solution is simple. Your program just echoes out whatever it has to echo out and it will appear in the terminal on real-time.

Now, in the case of webapp, you have two actors: server and client. If the server only responds when everything is complete, then after a long wait you will see 100% on the client-side, which is off course not what you expect. Now, you will need to 1. output the items on the server-side 2. get the progress as it happens from the client-side.

You can use a Websocket library, like Rachet . Beyond all the fancy words, websockets are duplex channels, kept open, where the client send info to the server and vice-versa. If you stick to websockets, then you will just need to have a websocket connection open and send update info to the client as progress happens.

You can use push notifications , as in this case the information flow is unidirectional.

You can save the actual progress somewhere and repeatedly request for it via AJAX polling .

There are also some hacky approaches, like the use of a forever frame, but I discourage you from looking them up or using them.

I have encoutered this type of problem you can output the progress of a script using ob_start() and ob_end_flush() functions

<?php

function rappel($buffer)
{
  // remplace toutes les pommes par des carottes
  return (str_replace("pommes de terre", "carottes", $buffer));
}

ob_start("rappel");

?>
<html>
<body>
<p>C'est comme comparer des carottes et des pommes de terre.</p>
</body>
</html>
<?php

ob_end_flush();

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM