piping data into command line php?

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.


You can pipe data in, yes. But it won't appear in $argv. It'll go to stdin. You can read this several ways, including fopen('php://stdin','r')

There are good examples in the manual


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 $argn

Simple example:

echo "hello world" | php -R 'echo str_replace("world","stackoverflow", $argn);'

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