It is possible to pipe data using unix pipes into a command-line php script? I've tried
$> data | php script.php
But the expected data
did not show up in $argv
. Is there a way to do this?
PHP can read from standard input, and also provides a nice shortcut for it: STDIN
.
With it, you can use things like stream_get_contents
and others to do things like:
$data = stream_get_contents(STDIN);
This will just dump all the piped data into $data
.
If you want to start processing before all data is read, or the input size is too big to fit into a variable, you can use:
while(!feof(STDIN)){ $line = fgets(STDIN); }
STDIN
is just a shortcut of $fh = fopen("php://stdin", "r");
. The same methods can be applied to reading and writing files, and tcp streams.
As I understand it, $argv
will show the arguments of the program, in other words:
php script.php arg1 arg2 arg3
But if you pipe data into PHP, you will have to read it from standard input. I've never tried this, but I think it's something like this:
$fp = readfile("php://stdin"); // read $fp as if it were a file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With