Input and Output Handling

suggest change

When run from the CLI, the constants STDIN, STDOUT, and STDERR are predefined. These constants are file handles, and can be considered equivalent to the results of running the following commands:

STDIN = fopen("php://stdin", "r");
STDOUT = fopen("php://stdout", "w");
STDERR = fopen("php://stderr", "w");

The constants can be used anywhere a standard file handle would be:

#!/usr/bin/php

while ($line = fgets(STDIN)) {
    $line = strtolower(trim($line));
    switch ($line) {
        case "bad":
            fprintf(STDERR, "%s is bad" . PHP_EOL, $line);
            break;
        case "quit":
            exit;
        default:
            fprintf(STDOUT, "%s is good" . PHP_EOL, $line);
            break;
    }
}

The builtin stream addresses referenced earlier (php://stdin, php://stdout, and php://stderr) can be used in place of filenames in most contexts:

file_put_contents('php://stdout', 'This is stdout content');
file_put_contents('php://stderr', 'This is stderr content');

// Open handle and write multiple times.
$stdout = fopen('php://stdout', 'w');

fwrite($stdout, 'Hello world from stdout' . PHP_EOL);
fwrite($stdout, 'Hello again');

fclose($stdout);

As an alternative, you can also use readline() for input, and you can also use echo or print or any other string printing functions for output.

$name = readline("Please enter your name:");
print "Hello, {$name}.";

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Command Line Interface CLI:
* Input and Output Handling

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
49 Command Line Interface CLI
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR