如何从 PHP 脚本中将数据通过管道传输到可执行文件中?
How do I pipe data into an executable from within a PHP script?
我有一个二进制文件,它从我在命令行上使用的 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
包装变量是否合适
感谢@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'));
returns
string(7) "`yeet` "
这正是我需要的输出!
我有一个二进制文件,它从我在命令行上使用的 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
包装变量是否合适
感谢@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'));
returns
string(7) "`yeet` "
这正是我需要的输出!