piping data into command line php?

2019-03-18 02:08发布

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?

8条回答
仙女界的扛把子
2楼-- · 2019-03-18 02:33

PHP can read from standard input, and also provides a nice shortcut for it: STDIN.

With it, you can 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.

查看更多
beautiful°
3楼-- · 2019-03-18 02:37

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);'
查看更多
一夜七次
4楼-- · 2019-03-18 02:38

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:

ls -ln | awk '{print $9}'

If you're looking to make a php script that behaves in a similar way, this worked for me:

#!/usr/bin/php
<?php

$input = stream_get_contents(fopen("php://stdin", "r"));

$lines = explode("\n", $input);

foreach($lines as $line) {
    $command = "php next_script.php '" . $line . "'";
    $output = shell_exec($command);
    echo $output;
}
查看更多
对你真心纯属浪费
5楼-- · 2019-03-18 02:40

If you want it to show up in $argv, try this:

echo "Whatever you want" | xargs php script.php

That would covert whatever goes into standard input into command line arguments.

查看更多
贼婆χ
6楼-- · 2019-03-18 02:43

This worked for me:

stream_get_contents(fopen("php://stdin", "r"));
查看更多
Deceive 欺骗
7楼-- · 2019-03-18 02:44

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
查看更多
登录 后发表回答