是否有可能在php中使用fopen获得404页面内容?

取消404警告后,fopen函数正确填充$http_response_header变量,但返回错误的句柄.

$opts = array(
  'http'=>array(
  'method'=>"GET",
  'header'=>"Accept-language: en\r\n"
  )
);
$context = stream_context_create($opts);
$old_eh = set_error_handler ( function () {});
$url = "https://wikimediafoundation.org/nonexisting";
$handle = fopen($url, 'r', false, $context);
var_dump($http_response_header);
var_dump($handle);

但是,在浏览器中打开此页面表明存在内容.我*在这里使用Curl吗?

也许我应该在$context变量中添加一些选项来更改此行为?

结果:

array(15) {
  [0]=> string(22) "HTTP/1.1 404 Not Found"
  [1]=> string(20) "Server: nginx/1.1.19"
  [2]=> string(35) "Date: Sat, 15 Feb 2014 16:23:41 GMT"
  [3]=> string(38) "Content-Type: text/html; charset=utf-8"
  [4]=> string(20) "Content-Length: 2858"
  [5]=> string(17) "Connection: close"
  [6]=> string(40) "X-Powered-By: PHP/5.3.10-1ubuntu3.9+wmf1"
  [7]=> string(48) "Cache-Control: s-maxage=2678400, max-age=2678400"
  [8]=> string(78) "X-Wikimedia-Debug: prot=https:// serv=wikimediafoundation.org loc=/nonexisting"
  [9]=> string(64) "Refresh: 5; url=https://wikimediafoundation.org/wiki/nonexisting"
  [10]=> string(33) "X-Varnish: 2541084702, 3538479758"
  [11]=> string(29) "Via: 1.1 varnish, 1.1 varnish"
  [12]=> string(20) "Accept-Ranges: bytes"
  [13]=> string(6) "Age: 0"
  [14]=> string(50) "X-Cache: cp1068 miss (0), cp1068 frontend miss (0)"
}
bool(false)

解决方法:

as per the manual将ignore_errors设置为true:

$opts = array(
  'http' => array(
      'method' => "GET",
      'header' => "Accept-language: en\r\n",
      'ignore_errors' => true
  )
);
上一篇:php-打开.gz文件并读取/替换


下一篇:PHP控制台脚本/传递默认参数/重构fopen()fread()fwrite()fclose()