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?
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 do things like:
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:
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.
If your
data
is on one like, you can also use either the -F or -R flag (-F reads & executes the file following it, -R executes it literally) If you use these flags the string that has been piped in will appear in the (regular) global variable $argnSimple example:
Came upon this post looking to make a script that behaves like a shell script, executing another command for each line of the input... ex:
If you're looking to make a php script that behaves in a similar way, this worked for me:
If you want it to show up in
$argv
, try this:That would covert whatever goes into standard input into command line arguments.
This worked for me:
As I understand it,
$argv
will show the arguments of the program, in other words: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: