PHP包含了以php://开头的一系列输出输出流,如php://stdin, php://stdout等。今天查看代码时,忽然想到一个问题:php://output和php://stdout有什么区别?

从PHP的官方文献中找答案,对输入流php://stdinphp://input的解释分别如下(输出流的解释过于简略):

php://stdinphp://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://inputphp://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.phpfile_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 outputmessage sent by stdoutmessage sent by printSAPI:cli

浏览器端请求,输出如下:

message sent by outputmessage sent by printSAPI:fpm-fcgi

在命令行下,PHP进程的标准输出流和结果输出流均指向终端,所有消息都打印出来。在浏览器端,PHP进程的输出流被忽略,只有结果数据流被发送到web服务器。同时,print和echo调用的信息都作为执行结果发往结果输出流,所以都正常显示。

最后再感慨一下PHP内置函数的简洁实用,一个file_put_contents函数就搞定流写入操作,换Java需要stream/writer一堆代码,也省去C风格的fopen/fwrite/fclose的繁琐。

推荐教程:PHP视频教程

更多相关文章

  1. php实现共享内存进程通信函数之shm
  2. php与java开发语言的明显区别
  3. php的use和require的区别
  4. php策略模式和适配器模式的区别
  5. PHP面向对象中new self( )和 new static( ) 的区别
  6. 多进程命名管通通信【无血缘关系进程】PHP 版本
  7. PHP中global与$GLOBALS的区别
  8. include,require,以及后缀加once的区别
  9. php中 continue break exit return 的区别

随机推荐

  1. Android如何判断手机卡是SIM卡或者USIM卡
  2. 简单介绍Android应用特色及详解四大组件
  3. 什么在Android M中被弃用?
  4. Android 3.2 以上转屏,切换屏幕,横竖屏(onC
  5. Android-SurfaceView拍照录像
  6. ListView的上拉弹簧、下拉弹簧,下拉弹簧时
  7. arcgis for android 开发的导航的部分 请
  8. Android 如何清空 Canvas 清屏只需三句
  9. Android:创建常见对话框以及使用对话框实
  10. 4.腾讯微博Android客户端开发——获取未