龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > php编程 >

PHP中的Streams详细介绍(2)

时间:2014-11-16 03:13来源:网络整理 作者:网络 点击:
分享到:
php://filter是一个元包装类,用于为stream增加filter功能。在使用readfile()或者file_get_contents()/stream_get_contents()打开stream时,filter将被使能。下面是一个例子:

php://filter是一个元包装类,用于为stream增加filter功能。在使用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可以修改或增强包装类的行为。例如使用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,这是个二位数组,可以通过$array['wrapper']['option_name']的形式来访问其中的参数。(注意每个包装类中context的options是不同的)。然后调用stream_context_get_default()来设置这些option,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);

Streams结论

精彩图集

赞助商链接