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
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!