简体   繁体   English

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

[英]Live output to a file with PHP exec()?

On Windows, I use PHP to execute a gulp command. 在Windows上,我使用PHP执行gulp命令。

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. 这行得通,但是我只能在命令完成后才能获得命令的结果,这大约需要30秒。

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. 我想在文件运行时将结果写入文件,以便可以使用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. 我已经尝试过shell_exec (), system ()和passthru (),但是我无法在PHP中使用它。

Any idea's ? 有任何想法吗 ?

Why not just call exec() in the way you proposed? 为什么不按照您提出的方式仅调用exec()

<?php

     set_time_limit(0);

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM