我正在使用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
}
发布于 2010-12-05 17:20:14
您需要检查HTTP response code
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');
}
发布于 2010-12-05 17:19:50
在PHP中使用这样的命令,您可以在它们前面加上一个@
来禁止这样的警告。
@file_get_contents('http://somenotrealurl.com/notrealpage');
如果出现故障,file_get_contents()将返回FALSE
,因此,如果您对照检查返回的结果,则可以处理该故障
$pageDocument = @file_get_contents('http://somenotrealurl.com/notrealpage');
if ($pageDocument === false) {
// Handle error
}
发布于 2013-12-23 17:38:18
每次使用http包装器调用file_get_contents
时,都会在本地范围内创建一个变量:$http_response_header
此变量包含所有HTTP标头。这种方法比get_headers()
函数更好,因为只执行一个请求。
注意:2个不同的请求可能以不同的方式结束。例如,get_headers()
将返回503,而file_get_contents()将返回200。您将获得正确的输出,但由于get_headers()调用中的503错误,您将不会使用它。
function getUrl($url) {
$content = file_get_contents($url);
// you can add some code to extract/parse response number from first header.
// For example from "HTTP/1.1 200 OK" string.
return array(
'headers' => $http_response_header,
'content' => $content
);
}
// Handle 40x and 50x errors
$response = getUrl("http://example.com/secret-message");
if ($response['content'] === FALSE)
echo $response['headers'][0]; // HTTP/1.1 401 Unauthorized
else
echo $response['content'];
这个方法还可以让你跟踪存储在不同变量中的少量请求头,因为如果你使用file_get_contents(),$http_response_header会在局部作用域中被覆盖。
https://stackoverflow.com/questions/4358130
复制相似问题