PHP Input and Output Handling

Download PHP for free

Example

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}.";
Restrict script execution to command line