PHP shell_exec在脚本运行时更新输出


PHP shell_exec update output as script is running

我正在使用脚本从服务器获取文件。我使用aria2快速下载文件,效果很好,但当脚本运行时,有没有办法输出命令中发生的事情。

例如,当你通过命令行运行这个命令时,你会每隔几秒钟更新一次

$output = shell_exec('aria2c http://myserver.com/myfile.rar');
echo "<pre>$output</pre>";

我得到这些输出:

[#f6a7c4 9.5MiB/1.7GiB(0%) CN:15 SD:5 DL:431KiB ETA:1h9m9s]
[#f6a7c4 52MiB/1.7GiB(2%) CN:23 SD:7 DL:0.9MiB ETA:30m19s]
[#f6a7c4 141MiB/1.7GiB(8%) CN:26 SD:4 DL:1.7MiB ETA:15m34s]

脚本只在完成执行后向我显示这些数据,可能长达5分钟以上,所以如果可能的话,我想知道发生了什么?

我尝试添加以下内容:

ob_start();
--Get URL for Files and show URL on screen
ob_flush();
--Start downloading file
ob_flush();

感谢

您需要打开一个进程描述符句柄来使用proc_open()异步读取,并使用stream_get_contents()从该流中读取。

您要下载的工具在末尾用'r字符刷新进度,这会覆盖实际行,因为没有后面的'n换行符。

http://www.php.net/manual/en/function.proc-open.php

请参考这些函数在php.net或谷歌上查找代码示例。

您应该更好地使用proc_open,而不是shell_exec()…:

<?php
    $cmd = 'wget http://192.168.10.30/p/myfile.rar';
    $pipes = array();
    $descriptors = array(
        0 => array("pipe", "r"),
        1 => array("pipe", "w"),
        2 => array("pipe", "w"),
    );
    $process = proc_open($cmd, $descriptors, $pipes) or die("Can't open process $cmd!");
    $output = "";
    while (!feof($pipes[2])) {
        $read = array($pipes[2]);
        stream_select($read, $write = NULL, $except = NULL, 0);
        if (!empty($read)) {
            $output .= fgets($pipes[2]);
        }
        # HERE PARSE $output TO UPDATE DOWNLOAD STATUS...
        print $output;
    }
    fclose($pipes[0]);
    fclose($pipes[1]);
    fclose($pipes[2]);
    proc_close($process);
    ?>

更新:是的,对不起,更正了几个错误…:-(

并且,请确保"aria2"可执行文件位于php环境的PATH中。。。为了安全起见,你应该在你的系统上指定它的完整路径。。。