php file_get_contents()请求远程页面如何添加头信息

时间:2016-08-31
php file_get_contents函数请求远程页面也可以像fsockopen函数一样来自定义自己请求的http头内容,本文章通过实例向大家介绍file_get_contents()函数如何设置头信息,需要的朋友可以参考一下。

在使用file_get_contents函数请求页面时,我们可以配置php.ini文件来发送user agent信息,那如何设置HTTP头信息呢?具体实现请看下面源码:

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

$context = stream_context_create($opts);
/*  http://www.manongjc.com/article/1425.html */
// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
?>