分析php:output和php:stdout的区别
PHP包含了以php://开头的⼀系列输出输出流,如php://stdin, php://stdout等。今天查看代码时,忽然想到⼀个问题:
fopen和open区别php://output和php://stdout有什么区别?
从PHP的官⽅⽂献中答案,对输⼊流php://stdin和php://input的解释分别如下(输出流的解释过于简略):
php://stdin
php://stdin, php://stdout and php://stderr allow direct access to the corresponding input or output stream of the
PHP process. The stream references a duplicate file descriptor, so if you open php://stdin and later close it, you
close only your copy of the descriptor-the actual stream referenced by STDIN is unaffected. Note that PHP
exhibited buggy behavior in this regard until PHP 5.2.1. It is recommended that you simply use the constants
STDIN, STDOUT and STDERR instead of manually opening streams using these wrappers.
php://stdin is read-only, whereas php://stdout and php://stderr are write-only.
php://input
php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST
requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on
special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by
default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data.
php://input is not available with enctype=”multipart/form-data”.
⽂档并未直接阐述两者的区别,仔细对⽐可得出以下信息:1. 均是只读流; 2. php://stdin是PHP进程的标准输⼊,php://input ⽤来读取请求正⽂的原始数据。通过这些信息,该如何正确认识两者的本质区别?
顺着php://stdin进程输⼊的提⽰,联想PHP进程的执⾏过程,再结合SAPI的差异,可以得到两者主要区别:php://stdin是PHP 进程的输⼊流,执⾏⽣命周期内均可能有数据流⼊(例如CLI下的交互式输⼊);php://input是PHP执⾏时的外部输⼊流,⼀般数据只能读⼀次(具体看SAPI的实现)。同理可得到php://stdout和php://output的区别:php://stdout是PHP进程的标准输出流,php://output是返回的结果数据流。
下⾯⽤代码验证结论:
// file: test.php
file_put_contents("php://output", "message sent by output" . PHP_EOL);
file_put_contents("php://stdout", "message sent by stdout" . PHP_EOL);
print("message sent by print" . PHP_EOL);
echo "SAPI:" , PHP_SAPI , PHP_EOL;
命令⾏执⾏⽂件,输出如下:
message sent by output
message sent by stdout
message sent by print
SAPI:cli
浏览器端请求,输出如下:
message sent by output
message sent by print
SAPI:fpm-fcgi
在命令⾏下,PHP进程的标准输出流和结果输出流均指向终端,所有消息都打印出来。在浏览器端,PH
P进程的输出流被忽略,只有结果数据流被发送到web服务器。同时,print和echo调⽤的信息都作为执⾏结果发往结果输出流,所以都正常显⽰。
最后再感慨⼀下PHP内置函数的简洁实⽤,⼀个file_put_contents函数就搞定流写⼊操作,换Java需要stream/writer⼀堆代码,也省去C风格的fopen/fwrite/fclose的繁琐。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论