How to read STDIN with PHP script from terminal

PHP STDIN stram files from CLIIn console environment PHP could be very useful especially running long tasks or for CRON jobs.

You can execute your script like:
[cc lang=”text”]php scriptName.php[/cc]
You can also pass some parameters like:
[cc lang=”text”]php scriptName.php param1 param2[/cc]
Those can be retrieved through a PHP variable which accessible only in console mode called $argv
[cc lang=”php”]
$param1 = $argv[1];
$param2 = $argv[2];
There is also another small trick that can parse the arguments into $_GET global array
[cc lang=”php”]parse_str(implode(‘&’, array_slice($argv, 1)), $_GET);[/cc]
That all looks very good but imagine you want to pass a file or even better a stream from the console that won’t be received as normal parameter though there is a way to get the data from the incoming stream which is very similar to reading files in PHP:
[cc lang=”php”]
$in = fopen(‘php://stdin’, ‘r’);
    $text = $text . fgets($in, 4096);
This block of code will read all incoming data the STDIN stream and append it to the $text variable. So how can you use it in the CLI here is an example
[cc lang=”text”]
php scriptName.php < fileData.txt cat someFile | php scriptName.php [/cc] Imagine you have a CSV file and you want to pass it to your script so that's how to do it simple and clean.


Just a guy with strong interest in PHP and Web technologies

Leave a Reply

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.