PHP Streams 概述与核心价值
Streams 是 PHP 提供的一项强力工具,日常开发中常会不经意间使用到。若能善加利用,将显著提升 PHP 的生产力;驾驭其强大功能后,应用程序的能力也将迈上新台阶。
关于 Streams 的定义,PHP 手册中有如下描述:
- Streams 在 PHP 4.3.0 版本中被引入,用于统一文件、网络、数据压缩等类似文件操作的方式,为这些操作提供一组通用的函数接口。简而言之,Stream 是一种具有流式行为的资源对象,允许以线性方式进行读写,并可通过 fseek() 跳转至 Stream 内的任意位置。
每个 Stream 对象都关联一个包装类(Wrapper),其中可添加处理特定协议和编码的代码。PHP 内置了多种常用包装类,同时也支持创建和注册自定义包装类。此外,还能利用现有的 Context 和 Filter 对包装类进行扩展和增强。
Stream 基础知识
Stream 通过 `scheme://` 的方式进行引用,其中 scheme 为包装类的名称,后续内容由该包装类的语法规则指定,不同包装类的语法存在差异。
PHP 默认的包装类是 file://,因此访问文件系统时实际上是在使用 Stream。例如,`readfile('/path/to/somefile.txt')` 与 `readfile('file:///path/to/somefile.txt')` 等效。若使用 `readfile('http://google.com/')`,PHP 则会调用 HTTP Stream 包装类进行操作。
如前所述,PHP 提供了丰富的内建包装类、协议及过滤器。可通过以下方式查询本机支持的包装类:
<?php
print_r(stream_get_transports());
print_r(stream_get_wrappers());
print_r(stream_get_filters());
在我机器上的输出结果为:
Array
(
[0] => tcp
[1] => udp
[2] => unix
[3] => udg
[4] => ssl
[5] => sslv3
[6] => sslv2
[7] => tls
)
Array
(
[0] => https
[1] => ftps
[2] => compress.zlib
[3] => compress.bzip2
[4] => php
[5] => file
[6] => glob
[7] => data
[8] => http
[9] => ftp
[10] => zip
[11] => phar
)
Array
(
[0] => zlib.*
[1] => bzip2.*
[2] => convert.iconv.*
[3] => string.rot13
[4] => string.toupper
[5] => string.tolower
[6] => string.strip_tags
[7] => convert.*
[8] => consumed
[9] => dechunk
[10] => mcrypt.*
[11] => mdecrypt.*
)
提供的功能非常丰富,看起来相当不错吧?
除了上述内建 Stream,还可以为 Amazon S3、MS Excel、Google Storage、Dropbox 甚至 Twitter 编写第三方 Stream 扩展。
php:// 包装类
PHP中内建了本语言用于处理I/O stream的包装类。可以分为几类,基础的有php://stdin,php://stdout, 以及php://stderr,这3个stream分别映射到默认 的I/O资源。同时PHP还提供了php://input,通过这个包装类可以使用只读的方式访问POST请求中的raw body。 这是一项非常有用的功能,特别是在处理那些将数据负载嵌入到POST请求中的远程服务时。
下面使用 cURL 工具进行简单测试:
curl -d "Hello World" -d "foo=bar&name=John" http://localhost/dev/streams/php_input.php
在 PHP 脚本中使用 print_r($_POST) 的测试结果如下所示:
Array
(
[foo] => bar
[name] => John
)
注意 $_POST 数组中无法访问到第一项数据。但如果使用 readfile('php://input'),结果则不同:
Hello World&foo=bar&name=John
PHP 5.1 增加了 php://memory 和 php://temp 这两个包装类,用于读写临时数据。正如命名所示,这些数据存储在底层系统的内存或临时文件中。
php://filter 是一个元包装类,用于为 Stream 增加过滤功能。在使用 readfile() 或 file_get_contents()/stream_get_contents() 打开 Stream 时,Filter 将被启用。示例如下:
<?php
// Write encoded data
file_put_contents("php://filter/write=string.rot13/resource=file:///path/to/somefile.txt","Hello World");
// Read data and encode/decode
readfile("php://filter/read=string.toupper|string.rot13/resource=http://www.google.com");
第一个例子使用 Filter 对保存到磁盘的数据进行编码处理;第二个例子使用两个级联 Filter 从远端 URL 读取数据。Filter 能为应用带来极为强大的功能。
Stream 上下文
Context 是一组与 Stream 相关的参数或选项,可用于修改或增强包装类的行为。例如,使用 Context 修改 HTTP 包装器是常见场景,这样无需 cURL 即可完成简单的网络操作。示例如下:
<?php
$opts = array(
'http'=>array(
'method'=>"POST",
'header'=> "Auth: SecretAuthTokenrn" .
"Content-type: application/x-www-form-urlencodedrn" .
"Content-length: " . strlen("Hello World"),
'content' => 'Hello World'
)
);
$default = stream_context_get_default($opts);
readfile('http://localhost/dev/streams/php_input.php');
首先定义一个 options 数组,这是一个二维数组,可通过 `$array['wrapper']['option_name']` 的形式访问参数(注意不同包装类的 Context Options 不同)。然后调用 stream_context_get_default() 设置这些选项,该函数同时返回默认 Context。设置完成后,调用 readfile() 即可应用已设置的 Context 抓取内容。
在上述例子中,内容被嵌入到 Request Body 中,远端脚本可使用 php://input 读取。同时,还能使用 apache_request_headers() 获取 Request Header,如下所示:
Array
(
[Host] => localhost
[Auth] => SecretAuthToken
[Content-type] => application/x-www-form-urlencoded
[Content-length] => 11
)
上述例子修改的是默认 Context 的参数,当然也可以创建新的 Context 交替使用。
<?php
$alternative = stream_context_create($other_opts);
readfile('http://localhost/dev/streams/php_input.php', false, $alternative);
结论
如何在现实世界中驾驭 Stream 的强大力量?它能带来什么实际好处?正如前文介绍,Stream 对所有文件系统相关功能进行了抽象。我首先想到的应用场景是使用虚拟文件系统包装类访问 PaaS 供应商的服务,例如 Heroku 或 AppFog,它们实际上没有真正的文件系统。使用 Stream 只需对应用程序稍作修改,即可将其移植到云端。接下来——在我的下一篇文章中——我将介绍如何编写自定义包装类以实现对特殊文件格式和编码格式的操作。