StarShows Studios
StarShows Studios

Reputation: 99

Run shell script from php and see complete progress?

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

Upvotes: 2

Views: 940

Answers (2)

jeremykenedy
jeremykenedy

Reputation: 4285

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

?>

Upvotes: 3

Psi
Psi

Reputation: 6783

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

Upvotes: 0

Related Questions