我们有一个命令行php应用程序,它维护特殊权限,并希望使用它来将管道数据中继到shell脚本中。
我知道我们可以通过以下方式阅读STDIN:
while(!feof(STDIN)){
$line = fgets(STDIN);
}
但是如何将该 STDIN 重定向到 shell 脚本中呢?
STDIN太大而无法加载到内存中,所以我不能做这样的事情:
shell_exec("echo ".STDIN." | script.sh");
将氙气的答案与 popen 一起使用似乎可以解决问题。
// Open the process handle
$ph = popen("./script.sh","w");
// This puts it into the file line by line.
while(($line = fgets(STDIN)) !== false){
// Put in line from STDIN. (Note that you may have to use `$line . ''n'`. I don't know
fputs($ph,$line);
}
pclose($ph);
正如@Devon所说,popen
/pclose
在这里非常有用。
$scriptHandle = popen("./script.sh","w");
while(($line = fgets(STDIN)) !== false){
fputs($scriptHandle,$line);
}
pclose($scriptHandle);
或者,对于较小的文件,可以采用类似fputs($scriptHandle, file_get_contents("php://stdin"));
行的方法代替逐行方法。