php IO流

PHP://Wrapper 是PHP自己的I/O流访问的封装

  • php://stdin:访问PHP进程相应的输入流,比如用在获取cli执行脚本时的键盘输入。
  • php://stdout:访问PHP进程相应的输出流。
  • php://stderr:访问PHP进程相应的错误输出。
  • php://input:访问请求的原始数据的只读流。
  • php://output:只写的数据流,以 print 和 echo 一样的方式写入到输出区。
  • php://fd:允许直接访问指定的文件描述符。例 php://fd/3 引用了文件描述符 3。
  • php://memory:允许读写临时数据。 把数据储存在内存中。
  • php://temp:同上,会在内存量达到预定义的限制后(默认是 2MB)存入临时文件中。
  • php://filter:过滤器。

php://stdin 是只读的, php://stdout 和 php://stderr 是只写的。

列举几个例子加深理解吧:

1. php://input

01//终端输入 curl -d "Hello World" -d "foo=bar&name=John"http://localhost/dev/streams/php_input.php
02//print_r($_POST)输出。注意丢失了第一个数据包
03 
04Array
05(
06    [foo] => bar
07    [name] => John
08)
09 
10// php://input输出
11Hello World&foo=bar&name=John

2. 使用过滤器

01//在使用 readfile(),file_get_contents(),stream_get_contents()之类的函数使,可以使用过滤器应用在打开的stream上
02 
03// 写入时用 str_rot13() 函数处理所有的流数据
04file_put_contents("php://filter/write=string.rot13/resource=file:///path/to/somefile.txt","Hello World");
05 
06//也可以使用下面的方式
07$h = fopen('test.txt', 'r');
08stream_filter_append($h, 'string.rot13');
09 
10// Read data and encode/decode
11readfile("php://filter/read=string.toupper|string.rot13/resource=http://www.google.com");

3. 设置上下文(Stream Contexts)

01$opts = array(
02  'http'=>array(
03    'method'=>"POST",
04    'header'=> "Auth: SecretAuthTokenrn" .
05               "Content-type: application/x-www-form-urlencodedrn" .
06               "Content-length: " . strlen("Hello World"),
07    'content' => 'Hello World'
08  )
09);
10$default = stream_context_get_default($opts);
11readfile('http://localhost/dev/streams/php_input.php',false,$default);
12//我们模拟了一个POST包
13//查看 php_input.php 的 apache_request_headers() 会显示结果
14 
15Array
16(
17    [Host] => localhost
18    [Auth] => SecretAuthToken
19    [Content-type] => application/x-www-form-urlencoded
20

    [Content-length] => 11

 

21

)

 

 

原文:http://www.nowamagic.net/academy/detail/12220509

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值