【问题标题】:Pipe stdin into a shell script through php通过 php 将 stdin 输入到 shell 脚本中
【发布时间】:2015-01-04 20:08:03
【问题描述】:

我们有一个命令行 php 应用程序,它维护着特殊权限,并希望使用它来将管道数据中继到 shell 脚本中。

我知道我们可以通过以下方式读取 STDIN:

while(!feof(STDIN)){
    $line = fgets(STDIN);
}

但是我怎样才能将该 STDIN 重定向到一个 shell 脚本中呢?

STDIN 太大而无法加载到内存中,所以我无法执行以下操作:

shell_exec("echo ".STDIN." | script.sh");

【问题讨论】:

    标签: php pipe stdin shell-exec


    【解决方案1】:

    将氙气的答案与 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);
    

    【讨论】:

      【解决方案2】:

      正如@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")); 的内容可能会代替逐行处理较小文件的方法。

      【讨论】:

      • 嗯,这应该执行而不是编写,但你的代码给了我一个想法。使用 popen 而不是 fopen 似乎可以解决问题。谢谢。
      猜你喜欢
      • 2019-09-16
      • 2017-01-15
      • 2014-04-30
      • 1970-01-01
      • 2012-09-06
      • 2011-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多