Search code examples
phpcommand-line-interfacestdin

php handling < file input from command line


I know that I can receive args on a command line/shell script like this:

!#/usr/bin/php
<?php
# file name - process.php
print_r($argv);

But what about redirects as follows:

#> ./process.php < input.txt

How do I read the file, and is input.txt a string argument or some type of file pointer already created?


Solution

  • Read from STDIN very similar to C:

    <?php
    $stdin = fopen('php://stdin', 'r');
    // Get the whole file, line by line:
    while (($line = fgets($stdin)) !== FALSE) {
        ...
    }
    ?>
    

    If you'd rather get the whole file contents into one variable, there's a shortcut:

    $contents = stream_get_contents(STDIN);