PHP standard input?

I know that PHP is usually used for web development where there is no standard input, but PHP claims that it can be used as a general-purpose scripting language if you follow it in contrived web conventions. I know that PHP prints to stdout (or whatever you want to call) with print and echo , which is quite simple, but I wonder how the PHP script can get input from stdin (especially with fgetc() , but any input function is good ), or is it even possible?

+47
php file-io stdin
Feb 16 '09 at 22:05
source share
9 answers

You can read stdin by creating a file descriptor for php://stdin , and then read it with fgets() for a string, for example (or, as you said, fgetc() for a single character):

 <?php $f = fopen( 'php://stdin', 'r' ); while( $line = fgets( $f ) ) { echo $line; } fclose( $f ); ?> 
+67
Feb 16 '09 at 22:08
source share

Reading from STDIN Recommended Way

 <?php while (FALSE !== ($line = fgets(STDIN))) { echo $line; } ?> 
+36
Dec 17 '10 at 23:22
source share

To avoid confusion with file descriptors, use file_get_contents() and php://stdin :

 $ echo 'Hello, World!' | php -r 'echo file_get_contents("php://stdin");' Hello, World! 

(If you are reading a truly huge amount of data from stdin , you can use the filehandle approach, but this should be good for many megabytes.)

+14
Feb 27 2018-12-12T00:
source share

A simple method is

 $var = trim(fgets(STDIN)); 
+11
Mar 26 2018-12-12T00:
source share

You can use fopen() in php://stdin :

 $f = fopen('php://stdin', 'r'); 
+8
Feb 16 '09 at 22:08
source share

Take it all in one shot:

 $contents = file_get_contents("php://stdin"); echo $contents; 
+6
Mar 10 '14 at 21:26
source share

IIRC, you can also use the following:

 $in = fopen(STDIN, "r"); $out = fopen(STDOUT, "w"); 

Technically the same, but a little cleaner syntactically.

+5
Feb 16 '09 at 23:09
source share

This also works:

 $data = stream_get_contents(STDIN); 
+2
Aug 14 '15 at 12:55
source share

When using fgets, it can block bash scripts if stdin not installed or is not empty, including when using the error control operator @ php .

 #!/usr/bin/php <?php $pipe = @trim(fgets(STDIN)); // Script was called with an empty stdin // Fail to continue, php warning 

This behavior can be avoided by setting stream_set_blocking in the php header:

 #!/usr/bin/php <?php stream_set_blocking(STDIN, 0); $pipe = @trim(fgets(STDIN)); // Script was called with an empty stdin // No errors or warnings, continue echo $pipe . "!"; 

As an example, it will be called as follows:

 echo "Hello world" | ./myPHPscript // Output "Hello world!" ./myPHPscript // Output "!" 
+2
Mar 05 '18 at 11:50
source share



All Articles