您的位置:首页 > 理论基础 > 计算机网络

PHP为fopen,file_get_contents等函数请求web地址时增加Http头的方法

2014-01-19 16:15 686 查看
我们在使用fsockopen时可以方便的自定义自己请求的http头内容来访问某些对客户端请求头有特殊限制的网站,但是使用fopen,file_get_contents等函数请求web地址时怎么来灵活定义请求的http头呢?

解决方案:stream_context_create() 函数

fopen实现

<?php
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);

$context = stream_context_create($opts);
$fp = fopen('http://www.example.com', 'r', false, $context);
fpassthru($fp);
fclose($fp);
?>

file_get_contents实现

<?php
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);

$context = stream_context_create($opts);

file_get_contents('http://www.example.com', null, $context);
?>


http://be-evil.org/post-174.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐