#native_company# #native_desc#
#native_cta#

Replacing Perl Scripts with PHP Scripts Page 3

By Jayesh Jain
on November 11, 2002

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:
stdin (‘php://stdin’)
stdout (‘php://stdout’)
stderr (‘php://stderr’)
The following example will display “Hello World” in the output window using the output stream.

<?php

    $stdout 
fopen('php://stdout''w');

    
fwrite($stdout,"Hello World");

    
fclose($stdout);

?>



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.

<?php

    $stdin 
fopen('php://stdin''r');

    echo 
"Please Enter your Name :";

    
$mystr fgets($stdin,100);

    echo 
"Your Name Is :n";

    echo 
$mystr;

    
fclose($stdin);

?>



The next example shows you how to output text to an error stream

<?php

    $stderr 
fopen('php://stderr''w');

    
fwrite($stderr,"There was an Error");

    
fclose($stderr);

?>



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.