为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
GCT1015 2019-09-19 10:53:25
我有一个PHP脚本可能需要至少10秒才能运行。我想为用户显示它的进度。在执行类中,我有一个属性$progress,它用进度(在1-100中)和一个方法get_progress()(其目的应该是显而易见的)更新。问题是,如何更新<progress>前端的元素供用户查看?我认为AJAX是解决方案,但我无法理解它。我无法访问同一个对象实例。
查看完整描述

3 回答

?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

我会把这里作为任何人搜索的参考 - 这完全依赖于没有javascript的...


<?php


/**

 * Quick and easy progress script

 * The script will slow iterate through an array and display progress as it goes.

 */


#First progress

$array1  = array(2, 4, 56, 3, 3);

$current = 0;


foreach ($array1 as $element) {

    $current++;

    outputProgress($current, count($array1));

}

echo "<br>";


#Second progress

$array2  = array(2, 4, 66, 54);

$current = 0;


foreach ($array2 as $element) {

    $current++;

    outputProgress($current, count($array2));

}


/**

 * Output span with progress.

 *

 * @param $current integer Current progress out of total

 * @param $total   integer Total steps required to complete

 */

function outputProgress($current, $total) {

    echo "<span style='position: absolute;z-index:$current;background:#FFF;'>" . round($current / $total * 100) . "% </span>";

    myFlush();

    sleep(1);

}


/**

 * Flush output buffer

 */

function myFlush() {

    echo(str_repeat(' ', 256));

    if (@ob_get_contents()) {

        @ob_end_flush();

    }

    flush();

}


?>


查看完整回答
反对 回复 2019-09-19
?
撒科打诨

TA贡献1934条经验 获得超2个赞

这有点困难,(FYI)PHP进程和你的AJAX请求由单独的线程处理,因此你无法获得$progress价值。

快速解决方案:您可以在$_SESSION['some_progress']每次更新时编写进度值,然后您的AJAX请求可以通过访问来获取进度值$_SESSION['some_progress']

您将需要JavaScript setInterval()setTimeout()继续调用AJAX处理程序,直到您获得返回为止100

它不是完美的解决方案,但它快速而简单。


因为您不能同时使用同一个会话两次,所以请改用数据库。将状态写入数据库,并使用间隔的AJAX调用从中读取。


查看完整回答
反对 回复 2019-09-19
  • 3 回答
  • 0 关注
  • 887 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信