首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >url不存在时的file_get_contents

url不存在时的file_get_contents
EN

Stack Overflow用户
提问于 2010-12-05 17:17:42
回答 6查看 94.9K关注 0票数 75

我正在使用file_get_contents()访问一个URL。

代码语言:javascript
复制
file_get_contents('http://somenotrealurl.com/notrealpage');

如果URL不是真实的,它将返回此错误消息。我如何才能让它优雅地出错,这样我才能知道该页面不存在,并在不显示此错误消息的情况下采取相应的操作呢?

代码语言:javascript
复制
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())

代码语言:javascript
复制
$client = New Zend_Http_Client();
$client->setUri('http://someurl.com/somepage');

$request = $client->request();

if ($request->isSuccessful()) {
 //do stuff with the result
}
EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2010-12-05 17:20:14

您需要检查HTTP response code

代码语言:javascript
复制
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');
}
票数 127
EN

Stack Overflow用户

发布于 2010-12-05 17:19:50

在PHP中使用这样的命令,您可以在它们前面加上一个@来禁止这样的警告。

代码语言:javascript
复制
@file_get_contents('http://somenotrealurl.com/notrealpage');

如果出现故障,file_get_contents()将返回FALSE,因此,如果您对照检查返回的结果,则可以处理该故障

代码语言:javascript
复制
$pageDocument = @file_get_contents('http://somenotrealurl.com/notrealpage');

if ($pageDocument === false) {
    // Handle error
}
票数 71
EN

Stack Overflow用户

发布于 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错误,您将不会使用它。

代码语言:javascript
复制
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会在局部作用域中被覆盖。

票数 31
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4358130

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档