使用PHP exec()实时输出到文件


Live output to a file with PHP exec()?

在Windows上,我使用PHP执行gulp命令。

像这样:

<?php
     set_time_limit(0);
     exec("cd /projectpath");
     $results = exec("gulp");
?>

这是有效的,但我只能在命令完成后才能得到结果,这大约需要30秒。

我想在运行时将结果写入文件,这样我就可以使用Ajax在一段时间内轮询进度。

在正常的命令提示符下,我可以进行

gulp > results.txt 2>&1

并且在命令运行时正在填充文本文件。

我已经尝试过shell_exec()、system()和passthru(),但我无法在PHP中实现这一点。

有什么想法吗?

为什么不按照您建议的方式调用exec()

<?php
     set_time_limit(0);
     exec("cd /projectpath");
     $results = exec("gulp > results.txt 2>&1");
?>

使用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)
}