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

时间:2023-03-09 10:03:28
PHP为fopen,file_get_contents等函数请求web地址时增加Http头的方法
我们在使用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