从php运行shell脚本并查看完整进度?

时间:2017-02-28 21:28:07

标签: php shell ubuntu nginx gulp

有没有办法从PHP运行shell脚本并在完成进度后回显结果?

这是我的shell脚本:

(它的多线 - 一些必须一个接一个地运行的命令。)

cd
cd /var/www/html/
npm uninstall gulp --save
npm install gulp --save
npm start

这是我目前正在运行的PHP脚本。它仅输出一些进度,仅在完成时输出。我需要预览进度。

    <?php
echo "loaded<br><br>";
 // echo shell_exec("cd /var/www/html/..");
// rin the shell scrip from header_register_callback
echo '<pre>';
// Outputs all the result of shellcommand "ls", and returns
// the last output line into $last_line. Stores the return value
// of the shell command in $retval.
$last_line = system('cd /var/www/html/; npm start', $retval);
// Printing additional info
echo '
</pre>
<hr />Last line of the output: ' . $last_line . '
<hr />Return value: ' . $retval;
?>

2 个答案:

答案 0 :(得分:3)

这是另一种方法。它使用redirection输出结果,然后使用file_get_contents()来读取输出。

<?php

echo "loaded<br><br>";

$cmd = 'npm start';
$run = $cmd . ' > result.txt 2> errors.txt';
$output = shell_exec($run);

$results = file_get_contents('result.txt');
if (strlen(file_get_contents('errors.txt')) != 0) {
  $results .= file_get_contents('errors.txt');
}

echo "<pre>$results</pre>";

?>

答案 1 :(得分:0)

我想,ob_flush()可行:

    <?php
echo "loaded<br><br>";
ob_flush();

 // echo shell_exec("cd /var/www/html/..");
// rin the shell scrip from header_register_callback
echo '<pre>';
ob_flush();
// Outputs all the result of shellcommand "ls", and returns
// the last output line into $last_line. Stores the return value
// of the shell command in $retval.
$last_line = system('cd /var/www/html/; npm start', $retval);
// Printing additional info
echo '
</pre>
<hr />Last line of the output: ' . $last_line . '
<hr />Return value: ' . $retval;
?>

但我不明白为什么在控制台上运行该脚本时会回显HTML标签...希望我帮你找对