2

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?

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

5 Comments

very concise answer. BTW: What is the < character referred to (and >) in shell scripting?
It doesn't have a specific name afaik but < and > are referred to as redirection operators.
Also, I am getting the MIME type echoed to STDOUT (regardless of whether I have any coding in the script or not). I.e. Content-type: text/html; charset=UTF-8 - how do I suppress this?
@OliverWilliams Something in your script (or maybe a library) is setting an HTTP header. To suppress header output on the CLI run PHP with php -h.
Matt I edited-suggested your answer, the hash-bang should look like #!/usr/bin/php -q to suppress this. Wild guess -q stands for quiet ;)
1

Oliver, instead of modifying a user's post, you should post a different answer. Here is what you intended to post:

#!/usr/bin/php -q
<?php
    //NOTE the -q switch in hashbang above, silences MIME type output when reading the file!
    $stdin = fopen('php://stdin', 'r');
    // Get the whole file, line by line:
    while (($line = fgets($stdin)) !== FALSE) {
        ...
    }
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.