Reading from standard input and writing to standard output or standard error using PHP

One of the most common command line tricks in Linux is to chain multiple commands using the pipe symbol i.e. you feed the output of one command as the input of another. This is called standard input and standard output redirection. PHP is usually used to program for the web but it can also be used as a shell scripting language to automate tasks and like any good shell scripting language it is possible to read from standard input and write to standard output using PHP.

To read from standard input you use php://stdin and to write to standard output you use php://stdout. For example reading standard input into a string variable and then echoing that variable:

$stdin = file_get_contents( 'php://stdin' ) ;
echo $stdin;

To write to standard output you use php://stdout:

$handle = fopen( 'php://stdout', 'w' ) ;
fwrite( $handle, "Hello World! \n" );
fclose( $handle );

The above code displays “Hello World!”. It’s equivalent to using the echo statement to write something on screen.

Two resource constants STDIN and STDOUT can also be used as file handles. This saves you from using fopen:

fwrite( STDOUT, "Hello World! \n" );

To write to standard error you can use php://stderr or the resource constant STDERR:

fwrite( STDERR, "ERROR ERROR! \n" );

Leave a Reply

Your email address will not be published.