Reading STDIN to PHP from the Command Line (CLI)

There may be times when you want to read from STDIN to a PHP script you’ve created from the command line.

Code below:

$in = fopen('php://stdin', 'r');
while(!feof($in)){
    $text = $text . fgets($in, 4096);
}

What this will do is read from STDIN, and create a $text variable of the contents.  It does this until the whole of STDIN has been read.

So:

cat file.txt | php my-php-file.php

… will put the contents of file.txt into the variable $text for use within the PHP script.