Using Streams in Scripts
You can redirect the output from any script to a file by running:
php world.php > outputfile
Note : All you linux fans, you can also redirect the script output to another command by using the | (pipe operator) eg : php world.php | sort
There are three streams available in PHP CLI, these are:
The following example will display “Hello World” in the output window using the output stream.
$stdout = fopen('php://stdout', 'w');
This example will demonstrate how to use an input stream, it will accept an input from the user, wait till user presses Enter key and then shall display the entered text.
$stdin = fopen('php://stdin', 'r');
echo "Please Enter your Name :";
$mystr = fgets($stdin,100);
echo "Your Name Is :n";
The next example shows you how to output text to an error stream
$stderr = fopen('php://stderr', 'w');
fwrite($stderr,"There was an Error");
Ok before we move ahead there are few things we should know, the output to the error stream is always send to the error device (normally the screen) and is not sent to a file or another command when redirecting the output. Always make sure you close the stream once you are done with it. Please refer to PHP manual if you need more information on fopen, fwrite, fgets and fclose functions.