猿问

显示长时间运行的PHP脚本的进度

我有一个PHP脚本可能需要至少10秒才能运行。我想为用户显示它的进度。

在执行类中,我有一个属性$progress,它用进度(在1-100中)和一个方法get_progress()(其目的应该是显而易见的)更新。

问题是,如何更新<progress>前端的元素供用户查看?

我认为AJAX是解决方案,但我无法理解它。我无法访问同一个对象实例。


GCT1015
浏览 888回答 3
3回答

幕布斯7119047

我会把这里作为任何人搜索的参考 - 这完全依赖于没有javascript的...<?php/**&nbsp;* Quick and easy progress script&nbsp;* The script will slow iterate through an array and display progress as it goes.&nbsp;*/#First progress$array1&nbsp; = array(2, 4, 56, 3, 3);$current = 0;foreach ($array1 as $element) {&nbsp; &nbsp; $current++;&nbsp; &nbsp; outputProgress($current, count($array1));}echo "<br>";#Second progress$array2&nbsp; = array(2, 4, 66, 54);$current = 0;foreach ($array2 as $element) {&nbsp; &nbsp; $current++;&nbsp; &nbsp; outputProgress($current, count($array2));}/**&nbsp;* Output span with progress.&nbsp;*&nbsp;* @param $current integer Current progress out of total&nbsp;* @param $total&nbsp; &nbsp;integer Total steps required to complete&nbsp;*/function outputProgress($current, $total) {&nbsp; &nbsp; echo "<span style='position: absolute;z-index:$current;background:#FFF;'>" . round($current / $total * 100) . "% </span>";&nbsp; &nbsp; myFlush();&nbsp; &nbsp; sleep(1);}/**&nbsp;* Flush output buffer&nbsp;*/function myFlush() {&nbsp; &nbsp; echo(str_repeat(' ', 256));&nbsp; &nbsp; if (@ob_get_contents()) {&nbsp; &nbsp; &nbsp; &nbsp; @ob_end_flush();&nbsp; &nbsp; }&nbsp; &nbsp; flush();}?>

撒科打诨

这有点困难,(FYI)PHP进程和你的AJAX请求由单独的线程处理,因此你无法获得$progress价值。快速解决方案:您可以在$_SESSION['some_progress']每次更新时编写进度值,然后您的AJAX请求可以通过访问来获取进度值$_SESSION['some_progress']。您将需要JavaScript&nbsp;setInterval()或setTimeout()继续调用AJAX处理程序,直到您获得返回为止100。它不是完美的解决方案,但它快速而简单。因为您不能同时使用同一个会话两次,所以请改用数据库。将状态写入数据库,并使用间隔的AJAX调用从中读取。
随时随地看视频慕课网APP
我要回答