问题
To my PHPeoples,
This is sort of a weird PHPuzzle, but I'm wondering if it's PHPossible.
The end goal is the equivalent functionality of
mysql mydb < file.sql
But with an API like this
./restore < file.sql
Where restore
is a PHP script like this
#!/usr/bin/env php
$cmd = "msyql mydb";
passthru($cmd, $status);
However, I want to pass STDIN to the passthru
command.
The clear benefit here is that I can put restore
somewhere in a pipeline and everything works peachy. Here's an example
# would be pretty awesome!
ssh $remote "msyqldump $config mydb | gzip" | gzip -dc | ./restore
Anyway, I doubt it's possible using passthru
, but perhaps with proc_open
in some way?
As a last case resort, in the event of an unsolvable PHPredicament, I would do something like this
./restore file.sql
With script like this
#!/usr/bin/env php
$cmd = sprintf("mysql mydb < %s", $argv[1]);
passthru($cmd, $status);
回答1:
PHPwnd
./restore
#!/usr/bin/env php
<?php
// set descriptors
$desc = array(
0 => array("file", "php://stdin", "r"),
1 => array("pipe", "w"),
2 => array("pipe", "w")
);
// open child proc
$proc = proc_open("mysql -uUSER -pPASS mydb", $desc, $pipes);
if (is_resource($proc)) {
// display child proc stdout
echo stream_get_contents($pipes[1]);
// close file streams
array_map('fclose', $pipes);
// get return value
$ret = proc_close($proc);
// display return value
printf("command returned %s\n", $ret);
}
Example use
cat file.sql.gz | gzip -dc | ./restore
回答2:
What! PHProfound!
Turns out passthru
already does this! PHenomenalP!
Check it out, PHPals:
gzip.php
#!/usr/bin/env php
<?php
passthru("gzip", $status);
if ($status !== 0) {
error_log("gzip exited with status %d", $status);
}
How PHProgressivist!
echo "hello" | php gzip.php | gzip -dc
Output
hello
来源:https://stackoverflow.com/questions/23587181/how-to-pipe-stdin-to-a-php-spawned-proc