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

时间:2011-08-13 08:06:02

标签: php ajax progress-bar

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

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

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

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

9 个答案:

答案 0 :(得分:51)

我会把这里作为任何人搜索的参考 - 这完全不依赖于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();
}

?>

答案 1 :(得分:40)

如果您的任务是上传大量数据集或在服务器上处理它,同时更新服务器的进度,您应该考虑使用某种作业架构,在那里启动作业并使用其他脚本执行此操作在服务器上运行(例如缩放/处理图像等)。在这种情况下,您一次只做一件事,从而形成一个任务管道,其中有一个输入和一个最终处理的输出。

在管道的每个步骤中,任务的状态在数据库内更新,然后可以通过目前存在的任何服务器推送机制发送给用户。运行一个处理上传和更新的脚本会在您的服务器上加载并限制您(如果浏览器关闭会发生什么,如果发生其他错误会怎样)。当进程分为多个步骤时,您可以从最后成功的位置恢复失败的任务。

有很多方法可以做到这一点。但整个流程看起来像这样

enter image description here

以下方法是我为个人项目所做的,这个脚本适用于将数千个高分辨率图像上传和处理到我的服务器,然后将其缩小为多个版本并上传到amazon s3,同时识别其中的对象。 (我的原始代码是在python中)

第1步:

启动传输或任务

首先上传您的内容,然后通过简单的POST请求立即返回此事务的事务ID或uuid。如果您在任务中执行多个文件或多个操作,您可能还希望在此步骤中处理该逻辑

第2步:

做好工作&amp;返回进度。

一旦弄清楚事务是如何发生的,您就可以使用任何服务器端推送技术来发送更新数据包。我会选择WebSocket或Server Sent Events,以适用于不支持的浏览器上的Long Polling。一个简单的SSE方法看起来像这样。

function TrackProgress(upload_id){

    var progress = document.getElementById(upload_id);
    var source = new EventSource('/status/task/' + upload_id );

    source.onmessage = function (event) {
        var data = getData(event); // your custom method to get data, i am just using json here
        progress.setAttribute('value', data.filesDone );
        progress.setAttribute('max', data.filesTotal );
        progress.setAttribute('min', 0);
    };
}

request.post("/me/photos",{
    files: files
}).then(function(data){
     return data.upload_id;
}).then(TrackProgress);

在服务器端,您需要创建一些跟踪任务的东西,一个简单的Job架构,其中job_id和发送到db的进度就足够了。我会把工作安排留给你和路由,但在那之后概念代码(对于最简单的SSE就足够了上面的代码)如下。

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
/* Other code to take care of how do you find how many files are left 
   this is really not required */
function sendStatusViaSSE($task_id){
    $status = getStatus($task_id);
    $json_payload = array('filesDone' => $status.files_done,
                          'filesTotal' => $status.files_total);
    echo 'data: ' . json_encode( $json_payload ) . '\n\n';
    ob_flush();
    flush();

    // End of the game
    if( $status.done ){
        die();
    }

}

while( True ){
     sendStatusViaSSE( $request.$task_id );
     sleep(4);
}

?>

可以在http://html5doctor.com/server-sent-events/

找到关于SSE的优秀教程

您可以在此问题Pushing updates from server

上阅读有关推送服务器更新的更多信息

上面是一个概念性的解释,还有其他方法可以实现这一目标,但这是解决方案,在我的案例中负责一项相当大的任务。

答案 2 :(得分:25)

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

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

您需要JavaScript的setInterval()setTimeout()来继续调用AJAX处理程序,直到您获得100的返回值。

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


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

答案 3 :(得分:12)

这是一个老问题,但我有类似的需求。我想用php system()命令运行一个脚本并显示输出。

我没有投票就完成了。

对于第二个Rikudoit案件应该是这样的:

JavaScript

document.getElementById("formatRaid").onclick=function(){
    var xhr = new XMLHttpRequest();     
    xhr.addEventListener("progress", function(evt) {
        var lines = evt.currentTarget.response.split("\n");
        if(lines.length)
           var progress = lines[lines.length-1];
        else
            var progress = 0;
        document.getElementById("progress").innerHTML = progress;
    }, false);
    xhr.open('POST', "getProgress.php", true);
    xhr.send();
}

PHP

<?php 
header('Content-Type: application/octet-stream');
header('Cache-Control: no-cache'); // recommended to prevent caching of event data.

// Turn off output buffering
ini_set('output_buffering', 'off');
// Turn off PHP output compression
ini_set('zlib.output_compression', false);
// Implicitly flush the buffer(s)
ini_set('implicit_flush', true);
ob_implicit_flush(true);
// Clear, and turn off output buffering
while (ob_get_level() > 0) {
    // Get the curent level
    $level = ob_get_level();
    // End the buffering
    ob_end_clean();
    // If the current level has not changed, abort
    if (ob_get_level() == $level) break;
}   

while($progress < 100) {
    // STUFF TO DO...
    echo '\n' . $progress;
}
?>

答案 4 :(得分:7)

解决方案是:

  1. Ajax轮询 - 在服务器端将进度存储在某处,然后使用ajax调用定期获取进度。

  2. 服务器发送事件 - 一种html5功能,允许从服务器发送的输出生成dom事件。对于这种情况,这是最佳解决方案,但IE 10不支持它。

  3. 脚本/ iframe流式传输 - 使用iframe流式传输来自长时间运行脚本的输出,该脚本会输出脚本标记作为可在浏览器中产生某些反应的间隔。

答案 5 :(得分:6)

在这里,我只想在@Jarod Law上面写的https://stackoverflow.com/a/7049321/2012407

之上添加两个问题。

确实非常简单有效。我调整和使用:) 所以我的两个问题是:

  1. 而不是使用setInterval()setTimeout()在回调中使用递归调用,如:

    function trackProgress()
    {
        $.getJSON(window.location, 'ajaxTrackProgress=1', function(response)
        {
            var progress = response.progress;
            $('#progress').text(progress);
    
            if (progress < 100) trackProgress();// You can add a delay here if you want it is not risky then.
        });
    }
    

    由于调用是异步的,否则可能会以不需要的顺序返回。

  2. 保存到$_SESSION['some_progress']很聪明,你可以,不需要数据库存储。 您实际需要的是允许同时调用两个脚本而不是PHP排队。所以你最需要的是session_write_close()! 我在这里发布了一个非常简单的演示示例:https://stackoverflow.com/a/38334673/2012407

答案 6 :(得分:4)

您是否考虑过输出javascript并使用流刷新?它看起来像这样

echo '<script type="text/javascript> update_progress('.($progress->get_progress()).');</script>';
flush();

由于刷新,此输出会立即发送到浏览器。从长时间运行的脚本中定期执行,它应该可以很好地工作。

答案 7 :(得分:1)

这是通过 $_SESSION['progress']session_start()session_write_close() 获得的最有效、最简单和经过测试的解决方案。

  1. 我们的想法是我们将进度保存在 $_SESSION['progress'] 中,然后锁定会话以通过 session_write_close() 不断向用户更新进度。

  2. 在迭代开始时使用 session_start();,在迭代结束时使用 session_write_close()

  3. 然后通过来自不同脚本的 ajax 获取此会话变量值 $_SESSION['progress']

  4. 然后在progress_bar等中通过ajax响应显示结果

现在让我们做一些代码:

创建一个表单/请求页面来触发 AJAX 请求(request.php):

<div id="demo">
<button type="button" class="button">Do Something</button>
</div>

 $("button").click(function(){
  $.ajax({url: "request-handler.php", success: function(result){
    alert('done');
  }});
});

request-handler.php

$total = 100;
$count = 1;
while(true)
{
    /*write your code
     ....
    here*/


    session_start();
    $percent = ($count *100)/$total;
    $_SESSION["progress"] = number_format((float)$percent, 2, '.', '');
    $_SESSION["progress"] = (int) ceil($percent);
    $count++;
    session_write_close();
}

Ajax 获取进度(front-view.php):

 <div class="progress" style="display: none;">
      <div class="progress-bar progress-bar-striped active" role="progressbar"
      aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width:0%">
        0%
      </div>
    </div>

    <div class="alert alert-success alert-dismissible" style="display: none;">
      <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
      <strong>Done!</strong> Successfully Done!.
    </div>

<script type="text/javascript">

  var pBar = $(".progress-bar");
  var progress = 0;
  var intervalId = window.setInterval(function(){
    $.get("get-progress.php", function(data, status){
      progress = data;
    });
    if(progress > 0)
    {
      pBar.parent().show();
    } 
    var percent = progress+'%';
    pBar.width(percent);
    pBar.html(percent);
    if(progress >= 100)
    {
      pBar.parent().hide();
     $ (".alert").show();
      clearInterval(intervalId);
    } 
     
  }, 2000);
    
 

       </script> 

get-progress.php:

<?php

session_start();

$progress = $_SESSION['progress'];
if ($progress >= 100) {
    session_start();
    unset($_SESSION['progress']);
}
//output the response
echo json_encode($progress);
?>

答案 8 :(得分:0)

在Web应用程序中,我们可能会向后端系统发出请求,这可能会触发长时间运行的进程,例如搜索大量数据或长时间运行的数据库进程。然后前端网页可能会挂起并等待该过程完成。在此过程中,如果我们可以向用户提供有关后端进程进度的一些信息,则可以改善用户体验。不幸的是,在Web应用程序中,这似乎不是一件容易的事,因为Web脚本语言不支持多线程,HTTP也是无状态的。我们现在可以使用AJAX来模拟实时过程。

基本上我们需要三个文件来处理请求。第一个是运行实际长时间运行作业的脚本,它需要有一个会话变量来存储进度。第二个脚本是状态脚本,它将在长时间运行的作业脚本中回显会话变量。最后一个是客户端AJAX脚本,它可以经常轮询状态脚本。

有关实施的详细信息,请参阅PHP to get long running process progress dynamically

相关问题