本文介绍了网址不存在时的file_get_contents的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用file_get_contents()访问URL.
I'm using file_get_contents() to access a URL.
file_get_contents('http://somenotrealurl.com/notrealpage');
如果URL不是真实的,它将返回此错误消息.我如何才能使其优雅地出错,以使我知道该页面不存在,并在不显示此错误消息的情况下采取相应措施?
If the URL is not real, it return this error message. How can I get it to error gracefully so that I know that the page doesn't exist and act accordingly without displaying this error message?
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())
for example in zend you can say: 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响应代码:
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');
}
这篇关于网址不存在时的file_get_contents的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!