PHP shell_exec update output as script is running

ぃ、小莉子 提交于 2019-12-11 11:45:41

问题


I'm using a script to get files from my server. I'm using aria2 to download the files quickly and it works great but is there a way when the script is running to output what is happening in the command.

For example when you run this command via command line you get updates every couple of seconds

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

I get these outputs:

[#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]

The script only shows me this data once it has finished executing, Which can be upto 5+ minutes so i would like to know whats going on if possible?

Ive tried adding the following:

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

Thanks


回答1:


You need to open a process descriptor handle to read asyncronously with proc_open() and read from this stream using stream_get_contents().

Your tool to download flushes the progress with a \r char at the end, which overwrites the actual line because there is no following \n newline char.

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

Please refer to these functions to find examples of code on php.net or google.




回答2:


You should better use proc_open, instead of 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);
    ?>

UPDATE: Yes, sorry, corrected a couple of errors... :-(

And, be sure "aria2" executable is in your php environment PATH... To be on the safe side, you should specify it's full path on your system...



来源:https://stackoverflow.com/questions/20614557/php-shell-exec-update-output-as-script-is-running

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!