php get_headers异常处理

时间:2012-07-17 08:24:14

标签: php exception-handling get-headers

我正在运行以下命令并获得异常:

  

$ headers = get_headers(“http://www.moneysupermarket.com/mortgages/”,1);

如何处理此异常(在我的情况下,忽略此url,因为它会导致异常)。

我试过了:

  1. 尝试/捕获
  2. 此链接中的代码:https://stackoverflow.com/a/6184127/1486303
  3. 但是,我仍然会出现此错误(我想忽略它)。

    谢谢!

2 个答案:

答案 0 :(得分:2)

新版

同样,这不是问题的正确答案,但避免错误,可以给出预期的结果。

get_headers在没有代理的情况下执行HTTP GET,因此 moneysupermarket.com 不喜欢它,因此请使用ini_set在请求中设置默认用户代理,并且一切正常:

ini_set("user_agent","Mozilla custom agent");
$headers = get_headers("http://www.moneysupermarket.com/mortgages/", 1);

PREVIOUS

显然,如果请求格式不正确,moneysupermarket.com会重置连接,请使用cUrl执行请求(从curl手册页获取):

// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.moneysupermarket.com/mortgages/");
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla custom agent");

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);

答案 1 :(得分:2)

也不例外。 get_headers()在出错时返回FALSE。虽然有一条警告信息,但这也不例外,因此无法获取。有关警告和其他错误,请参阅:http://www.php.net/manual/en/function.set-error-handler.php