简体   繁体   English

从 PHP 中的 popen 打印出一行到屏幕?

[英]Printing out one line to screen from popen in PHP?

I'm making a batch megadownload site in PHP.我正在 PHP 中创建一个批量下载站点。 I'm parsing the input, validating it, then passing it to a bash script.我正在解析输入,对其进行验证,然后将其传递给 bash 脚本。 Im piping the output to the web page, but the contents of the webpage show like this.我将 output 输送到 web 页面,但网页内容显示如下。

8lX0JsBi.part01.rar: 0.00% - 0 bytes of 1000.0?MiB
8lX0JsBi.part01.rar: 0.09% - 917.7?KiB (939752 bytes) of 1000.0?MiB (916.7?KiB/s)
8lX0JsBi.part01.rar: 0.63% - 6.3?MiB (6566240 bytes) of 1000.0?MiB (5.3?MiB/s)
8lX0JsBi.part01.rar: 1.38% - 13.8?MiB (14430560 bytes) of 1000.0?MiB (7.0?MiB/s)
8lX0JsBi.part01.rar: 2.30% - 23.0?MiB (24129888 bytes) of 1000.0?MiB (9.0?MiB/s)

I'd like it to just show one line at aa time that updates a single line.我希望它一次只显示一行更新一行。

8lX0JsBi.part01.rar: 2.30% - 23.0?MiB (24129888 bytes) of 1000.0?MiB (9.0?MiB/s)

Here is the function I'm using to pipe stdout to the webpage.这是我正在使用的 function 到网页的 pipe 标准输出。

<?php
/**
 * Execute the given command by displaying console output live to the user.
 *  @param  string  cmd          :  command to be executed
 *  @return array   exit_status  :  exit status of the executed command
 *                  output       :  console output of the executed command
 */
function liveExecuteCommand($cmd)
{

    while (@ ob_end_flush()); // end all output buffers if any

    $proc = popen("$cmd 2>&1 ; echo Exit status : $?", 'r');

    $live_output     = "";
    $complete_output = "";

    while (!feof($proc))
    {
        $live_output     = fread($proc, 4096);
        $complete_output = $complete_output . $live_output;
        echo "$live_output";
        @ flush();
    }

    pclose($proc);

    // get exit status
    preg_match('/[0-9]+$/', $complete_output, $matches);

    // return exit status and intended output
    return array (
                    'exit_status'  => intval($matches[0]),
                    'output'       => str_replace("Exit status : " . $matches[0], '', $complete_output)
                 );
}
?>

You have a few options:你有几个选择:

Using clear, though this will clear the entire console.使用 clear,虽然这会清除整个控制台。

system('clear');
echo '5%';
sleep(5);
system('clear');
echo '10%';

Or using /r, This will replace the last printed out line.或者使用 /r,这将替换最后打印出来的行。

echo "5%";
sleep(5);
echo "\r10%";

You can also user cursor manipulation and character counting or the output buffer.您还可以使用 cursor 操作和字符计数或 output 缓冲区。 But I think that will be a bit much for this.但我认为这会有点多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM