代码之家  ›  专栏  ›  技术社区  ›  Brian Leishman

如何将数据从PHP脚本中导入可执行文件?

  •  1
  • Brian Leishman  · 技术社区  · 6 年前

    我有一个二进制文件,它从命令行上使用的stdin中获取输入,通过管道将文件内容传输到它,就像 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 回复  |  直到 6 年前
        1
  •  0
  •   Brian Leishman    6 年前

    感谢@NigelRen在正确方向上的观点 proc_open

    我将这些步骤包装在一个函数中,以便稍后使用,这可能会有所帮助。

    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'));
    

    退货

    string(7) "`yeet` "
    

    这正是我需要的输出!