php://output和php://stdout的区别-php教程

资源魔 34 0
PHP蕴含了以php://扫尾的一系列输入输入流,如php://stdin, php://stdout等。明天查看代码时,突然想到一个成绩: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 reco妹妹ended 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过程的规范输入流以及后果输入流均指向终端,一切音讯都打印进去。正在阅读器端,PHP过程的输入流被疏忽,只有后果数据流被发送到web效劳器。同时,print以及echo挪用的信息都作为执行后果发往后果输入流,以是都失常显示。

最初再感叹一下PHP内置函数的简约适用,一个file_put_contents函数就搞定流写入操作,换Java需求stream/writer一堆代码,也省去C格调的fopen/fwrite/fclose的繁琐。

保举教程:PHP视频教程

以上就是php://output以及php://stdout的区分的具体内容,更多请存眷资源魔其它相干文章!

标签: php php开发教程 php开发资料 php开发自学

抱歉,评论功能暂时关闭!