php中的上下文能够用于各种文件流和数据流,能让使用者对数据的获取达到个性化的需求和更精细的控制。
举例来说,当我们想要抓取一个页面内容时,最简单直接就是使用file_get_contents方法
$html = file_get_contents('http://blog.csdn.net'); //抓取csdn博客首页
这样只局限用get方式访问,如果是post方式抓取页面貌似就办不到了,这时我们一般做法都会换用功能更强大的curl处理,其实file_get_contents也是可以使用POST方法的,方法就是使用php的上下文(Context)来控制,这里先准备一个页面来当作被抓取页面,代码很简单
<?php
//data.php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
echo 'POST: ' . http_build_query($_POST);
}
else
{
echo 'GET: ' . http_build_query($_GET);
}
使用Context:
<?php
$post = array(
'name' => 'jerry'
);
$opts = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($post)
)
);
$context = stream_context_create($opts); //创建上下文对象
echo file_get_contents('http://127.0.0.1:8080/data.php', NULL, $context);
运行结果
POST: name=jerry
创建context的参数很多,opts的格式为: $arr['wrapper']['option'] = $value ,其中wrapper是支持的多种封装协议之一,目前支持以下几种:
Socket context options — Socket context option listing
HTTP context options — HTTP context option listing
FTP context options — FTP context option listing
SSL context options — SSL context option listing
CURL context options — CURL context option listing
Phar context options — Phar context option listing
MongoDB context options — MongoDB context option listing
Context parameters — Context parameter listing
Zip context options — Zip context option listing
每一种 wrapper 的 option 又不尽相同, 具体请查看手册每种wrapper支持的参数: http://php.net/manual/zh/context.php
除了创建context 时指定 $options外, 也可以创建context 后再使用 stream_context_set_option 函数设置 $options
例如:
$post = array(
'name' => 'jerry'
);
$opts = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($post)
)
);
$context = stream_context_create();
stream_context_set_option($context, $opts);
一个使用本地指定端口去连接服务器的例子(不指定的情况下会随机使用一个可用的端口去连接服务器):
// connect to the internet using port '7000'
$opts = array(
'socket' => array(
'bindto' => '0:7000',
),
);
// create the context...
$context = stream_context_create($opts);
// ...and use it to fetch the data
echo file_get_contents('http://www.example.com', false, $context);
That's it!