我正在使用 file_get_contents() 访问 URL。
file_get_contents('http://somenotrealurl.com/notrealpage');
如果 URL 不真实,则返回此错误消息。如何让它优雅地出错,以便我知道该页面不存在并采取相应的操作而不显示此错误消息?
file_get_contents('http://somenotrealurl.com/notrealpage')
[function.file-get-contents]:
failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found
in myphppage.php on line 3
例如在 zend 中你可以说:if ($request->isSuccessful())
$client = New Zend_Http_Client();
$client->setUri('http://someurl.com/somepage');
$request = $client->request();
if ($request->isSuccessful()) {
//do stuff with the result
}
您需要检查HTTP 响应代码 https://developer.mozilla.org/en-US/docs/HTTP/HTTP_response_codes:
function get_http_response_code($url) {
$headers = get_headers($url);
return substr($headers[0], 9, 3);
}
if(get_http_response_code('http://somenotrealurl.com/notrealpage') != "200"){
echo "error";
}else{
file_get_contents('http://somenotrealurl.com/notrealpage');
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)