dtvx3420
dtvx3420
2017-02-28 21:28

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

Is there a way to run a shell script from PHP and echo the results after progress is completed?

Here is my shell script:

(Its multilines - a few commands that have to be ran one after the other. )

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

here's my currently functioning PHP script. It only outputs some of the progress and only outputs it when complete. I need a live preview of the progress.

    <?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条回答

  • duanqiao1947 duanqiao1947 4年前

    Here is another approach. It uses redirection to output the results and then file_get_contents() to read the output.

    <?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>";
    
    ?>
    
    点赞 评论 复制链接分享
  • drrw8672 drrw8672 4年前

    I guess, ob_flush() would work:

        <?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;
    ?>
    

    But I don't understand why you echo HTML-tags when you run that script on the console... Hope I got you right

    点赞 评论 复制链接分享

相关推荐