Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

piping data into command line php?

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?

like image 413
user151841 Avatar asked May 05 '11 02:05

user151841


2 Answers

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.

like image 134
hawken Avatar answered Sep 24 '22 00:09

hawken


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 
like image 25
Gustav Larsson Avatar answered Sep 21 '22 00:09

Gustav Larsson