Input and Output Handling
suggest changeWhen run from the CLI, the constants STDIN, STDOUT, and STDERR are predefined file handles. They are not variables, so the names cannot be assigned. They correspond to:
fopen("php://stdin", "r"); // STDIN
fopen("php://stdout", "w"); // STDOUT
fopen("php://stderr", "w"); // STDERR
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);
readline() reads a line when the readline extension is available. echo and print write to standard output.
$name = readline("Please enter your name:");
print "Hello, {$name}.";
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents