php fopen请求远程页面如何设置http头信息

时间:2016-09-05
想使用fopen函数打开一个远程图片,但是该页面的图片只能被设置了cookie的用户所访问到,所以在使用fopen函数之前,我们必须为fopen请求设置http头信息,具体如何设置http头信息请看下面源码。

我们可以通过stream_context_create函数设置fopen请求的http头信息。具体实现代码如下:

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

$context = stream_context_create($opts);

/* Sends an http request to www.example.com
   with additional headers shown above */
$fp = fopen('http://www.example.com', 'r', false, $context);
fpassthru($fp);
fclose($fp);
?>