I know PHP is usually used for web development, where there is no standard input, but PHP claims to be usable as a general-purpose scripting language, if you do follow it's funky web-based conventions. I know that PHP prints to stdout
(or whatever you want to call it) with print
and echo
, which is simple enough, but I'm wondering how a PHP script might get input from stdin
(specifically with fgetc()
, but any input function is good), or is this even possible?
php://stdin, php://stdout and php://stderr allow direct access to standard input stream device, standard output stream and error stream to a PHP process respectively. Predefined constants STDIN, STDOUT and STDERR respectively represent these streams.
php://stdin, php://stdout and php://stderr allow direct access to the corresponding input or output stream of the PHP process. The stream references a duplicate file descriptor, so if you open php://stdin and later close it, you close only your copy of the descriptor-the actual stream referenced by STDIN is unaffected.
php://input is a read-only stream that allows you to read raw data from the request body. php://input is not available with enctype="multipart/form-data" .
file_get_contents() function: This function in PHP is used to read a file into a string. json_decode() function: This function takes a JSON string and converts it into a PHP variable that may be an array or an object.
It is possible to read the stdin
by creating a file handle to php://stdin
and then read from it with fgets()
for a line for example (or, as you already stated, fgetc()
for a single character):
<?php $f = fopen( 'php://stdin', 'r' ); while( $line = fgets( $f ) ) { echo $line; } fclose( $f ); ?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With