编 写:袁 亮
时 间:2015-07-17
说 明:file_get_contents了解:自定义http请求
一、使用原因
1、这是一个使用非常频繁的函数,对应的file_put_contents,都是文件操作中第一选择
2、抓取网络内容,一般情况下,也是使用的这个,但遇到稍微麻烦点的,我们就觉得没法子了
3、curl等能做的,其实file_get_contents也基本上都能做,只是大家不熟悉
二、简单范例,直接看php.net
array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
三、核心函数 stream_context_create
1、支持以下协议,生成相应资源流上下文
http://php.net/manual/zh/wrappers.php
file:// — 访问本地文件系统
http:// — 访问 HTTP(s) 网址
ftp:// — 访问 FTP(s) URLs
php:// — 访问各个输入/输出流(I/O streams)
zlib:// — 压缩流
data:// — 数据(RFC 2397)
glob:// — 查找匹配的文件路径模式
phar:// — PHP 归档
ssh2:// — Secure Shell 2
rar:// — RAR
ogg:// — 音频流
expect:// — 处理交互式的流
2、http资源流支持参数:
http:http://php.net/manual/zh/context.http.php
http协议支持的参数,基本都支持
header头,post数据,user_agent,代理,超时,跟随重定向等等
3、post数据设置范例
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/submit.php', false, $context);