Created
December 13, 2016 17:56
-
-
Save theharveyz/871f58d00a763554dfd68fcb5887b0e2 to your computer and use it in GitHub Desktop.
php stream流操作相关知识点
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* stream解释: 将数据从开始位置传送到目的位置, 可以是大流量文件传输 | |
* 1. stream的过程: | |
* 开始通信 | |
* 读取数据 | |
* 写入数据 | |
* 结束通信 | |
* ## 可以说stream是这一过程的抽象 | |
* | |
* 2. steam相关操作函数: | |
* fopen | |
* fgets | |
* fgetc | |
* fwrite | |
* fputs | |
* fseek | |
* feof | |
* fclose | |
* file_exists | |
* file_get_contents/file_put_contents | |
* 3. 协议封装: <scheme>://<target> | |
* [显式使用]file://xxx 默认会省略file://而直接跟着xxx | |
* sftp://xxxx | |
* http://xxxx | |
* php://stdin 命令只读流 | |
* php://stdout 命令行只写流 | |
* php://memory 从内存中读取或者写入数据: 危险操作,因为内存有限 | |
* php://temp 也是从内存中写入或者读取数据, 当内存不足时, 则写入临时目录 | |
* 4. 流上下文对象: 可以构造出在管道中传输的对象: | |
* stream_context_create() | |
* 例如: 构造http post请求 | |
*/ | |
$reqBody = json_encode([ | |
'foo' => 'bar' | |
]); | |
$context = stream_context_create([ | |
'http' => [ | |
'method' => 'POST', | |
'header' => [ | |
"Content-Type: application/json;charset=utf-8;\r\n", | |
"Content-Length:" . mb_strlen($reqBody) | |
] | |
] | |
]); | |
file_get_contents('http://example.con', false, $context); // 注意这里是file_get_contents而不是put | |
/** | |
* 5. 流过滤器: | |
* - 通过stream_filter_append($fd, 'filter')进行追加 | |
* - 或者: 通过 | |
* php://filter/read=<filename>/resource=<scheme>://<target> 过滤流 | |
* 6. 自定义用户过滤器 | |
* - 继承: php_user_filter | |
* - 必须实现: onCreate(), onClose(), filter方法 | |
* - filter参数: | |
* - $in // 流来的 桶队列 | |
* - $out // 流去的桶队列 | |
* - &$consumed // 处理的字节数 | |
* - $closing // 是流中最后一个桶队列吗? | |
* - 桶队列: | |
* - 一个流中可能包含多个桶队列 | |
* - 每个桶队列中的桶的属性有: | |
* - data: bucket数据 | |
* - datalen: bucket的数据长度 | |
* - stream_bucket_make_writeable($in) | |
* - 把桶流向下游: stream_bucket_append($bucket, $out) | |
* - 需要通过 stream_filter_register注册 | |
*/ | |
class DemoStreamFilter extends php_user_filter | |
{ | |
public function filter($in, $out, &$consumed, $closing) | |
{ | |
// 遍历桶队列 | |
while($bucket = stream_bucket_make_writeable($in)) { | |
// 增加已经处理的长度 | |
$consumed += $bucket->datalen; | |
// .... | |
stream_bucket_append($bucket, $out); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment