Similarly what is the difference between php://output
and php://stdout
?
I was trying to figure out how servers provide php://input
and php://output
. The only way I could think of (given that both php://input
and php://output
are independent of the mysterious php.ini file according to this page in the manual) would be to change stdin
and stdout
to both refer to the connection socket's file descriptor. But then to my chagrin I found out that php://stdin
and php://stdout
were also defined - presumably in a different way.
Is this just redundancy or do these file names actually refer to do different things? Can someone tell me what's going on here?
The difference is in the environment where you're expected to use them. php://stdin
, php://stdout
, and php://stderr
are mapped directly to the relevant POSIX file streams and are intended for use with the CLI SAPI. On the other hand, php://input
and php://output
are intended for use with web-based SAPIs.
Try running these two commands from the command line:
printf "foo" | php -r "var_dump(file_get_contents('php://stdin'));"
printf "foo" | php -r "var_dump(file_get_contents('php://input'));"
You're going to get output like this:
Command line code:1:
string(3) "foo"
Command line code:1:
string(0) ""
Because php://input
expects to be used by a web SAPI like CGI or mod_php and will not get the contents of STDIN passed to it. Likewise, trying to read raw POST data (the only real use for php://input
) using php://stdin
would fail.
php://output
can generally be used in both environments but it's rarely used at all, since one can simply echo
output. php://stdout
is the more logical choice for command line code, though again it's generally easier to just use echo
.
php://stderr
is of course invaluable to command line programmers who need to output informational, debug, or error messages to a different stream than the program output.