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

  • 写回答

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!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100