zoukankan      html  css  js  c++  java
  • 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

     1 //终端输入 curl -d "Hello World" -d "foo=bar&name=John" http://localhost/dev/streams/php_input.php
     2 //print_r($_POST)输出。注意丢失了第一个数据包
     3 
     4 Array
     5 (
     6     [foo] => bar
     7     [name] => John
     8 )
     9 
    10 // php://input输出
    11 Hello World&foo=bar&name=John

      2. 使用过滤器

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

      3. 设置上下文(Stream Contexts)  

     1 $opts = array(
     2   'http'=>array(
     3     'method'=>"POST",
     4     'header'=> "Auth: SecretAuthTokenrn" .
     5                "Content-type: application/x-www-form-urlencodedrn" .
     6                "Content-length: " . strlen("Hello World"),
     7     'content' => 'Hello World'
     8   )
     9 );
    10 $default = stream_context_get_default($opts);
    11 readfile('http://localhost/dev/streams/php_input.php',false,$default);
    12 //我们模拟了一个POST包
    13 //查看 php_input.php 的 apache_request_headers() 会显示结果
    14 
    15 Array
    16 (
    17     [Host] => localhost
    18     [Auth] => SecretAuthToken
    19     [Content-type] => application/x-www-form-urlencoded
    20     [Content-length] => 11
    21 )
  • 相关阅读:
    线程安全和非线程安全
    spring MVC和hibernate的结合
    Spring学习笔记1——基础知识 (转)
    bitset && Luogu 3674 小清新人渣的本愿
    luogu P3452 [POI2007]BIU-Offices
    每日刷题记录
    Codeforces Round #721 (Div. 2) B2. Palindrome Game (hard version)
    2019湘潭邀请赛A
    2021CCPC浙江省赛 B
    Codeforces Round #720 (Div. 2) D
  • 原文地址:https://www.cnblogs.com/loveyouyou616/p/5970290.html
Copyright © 2011-2022 走看看