dongqishun6409
2018-03-21 14:46
浏览 73
已采纳

如何从PHP脚本中将数据传输到可执行文件中?

I have a binary that takes input from stdin that I use on the command line by piping file contents to it like cat query.sql | go-mysql-format, but how do I pipe a variable to the executable?

Currently I have

file_put_contents($File = "$_SERVER[DOCUMENT_ROOT]/tmp/" . uuid(), $MySQL);
$o = shell_exec('cat ' . escapeshellarg($File) . ' | go-mysql-format --html');

Basically I would like to skip the file creation.

It's also important to note that the data will contain newlines, so I'm not sure wrapping the variable with escapeshellarg will be appropriate

图片转代码服务由CSDN问答提供 功能建议

我有一个二进制文件,它通过将文件内容传递给它来获取我在命令行上使用的stdin的输入,就像< code> cat query.sql | go-mysql-format ,但是如何将变量传递给可执行文件?

目前我有

  file_put_contents  ($ File =“$ _SERVER [DOCUMENT_ROOT] / tmp /”。uuid(),$ MySQL); 
 $ o = shell_exec('cat'.escapeshellarg($ File)。'| go-mysql-format --html  '); 
   
 
 

基本上我想跳过文件创建。

同样重要的是要注意数据将包含换行符,因此我不确定用 escapeshellarg 包装变量是否合适

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanji7881 2018-03-21 15:05
    已采纳

    Thanks to the point in the right direction from @NigelRen to look at proc_open

    I wrapped the steps in a function for me to use later, which might be helpful.

    function exec_stdin(string $Command, string $Data) {
        $_ = proc_open($Command, [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']], $p);
        if (is_resource($_)) {
            fwrite($p[0], $Data);
            fclose($p[0]);
            $o = stream_get_contents($p[1]);
            fclose($p[1]);
    
            $_ = proc_close($_);
    
            return $o;
        }
    
        return false;
    }
    
    var_dump(exec_stdin('go-mysql-format', 'yeet'));
    

    returns

    string(7) "`yeet` "
    

    which is exactly the output I needed!

    点赞 打赏 评论

相关推荐 更多相似问题