0

On Windows, I use PHP to execute a gulp command.

Like this :

<?php

     set_time_limit(0);

     exec("cd /projectpath");
     $results = exec("gulp");
?>

This works, but I can only get the results of the command after it has finished, which takes about 30 seconds.

I would like to write the results to a file, while it is running, so I can poll the progress in an interval using Ajax.

In a normal command prompt I can do

gulp > results.txt 2>&1

and the text file is being filled while the command is running.

I already tried shell_exec(), system() and passthru() too, but I can't get this to work from within PHP.

Any idea's ?

Dylan
  • 9,129
  • 20
  • 96
  • 153

2 Answers2

0

Why not just call exec() in the way you proposed?

<?php

     set_time_limit(0);

     exec("cd /projectpath");
     $results = exec("gulp > results.txt 2>&1");
?>
Andreas
  • 2,821
  • 25
  • 30
  • I tried this of course, but the command seems to stop immediately then and does nothing. No idea why. – Dylan May 01 '16 at 19:32
0

Use proc_open:

<?php
$cmd = 'for i in $(seq 20); do sleep 1; echo $i; done';
$cwd = '/';
$descriptors = array(
    0 => array('pipe', 'r'),
    1 => array('file', 'stdout', 'w'),
    2 => array('file', 'stderr', 'w'),
);

$handle = proc_open($cmd, $descriptors, $pipes, $cwd);
if (!$handle) {
    echo 'failed to run command';
} else {
    proc_close($handle); // wait for command to finish (optional)
}
phihag
  • 278,196
  • 72
  • 453
  • 469
  • I came across this example, but couldn't really understand what was happening in it. Where does this write the results to ? How to use it in my example? – Dylan May 01 '16 at 19:33
  • `$cwd` should be set to `'/projectpath'`, `$cmd = 'gulp';`, and then replace `stdout` and `stderr` with the filenames where you want to have stdout and stderr. – phihag May 01 '16 at 19:41