当 url 不存在时 file_get_contents

发布于 2024-10-06 06:21:03 字数 688 浏览 4 评论 0原文

我正在使用 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
}

I'm using file_get_contents() to access a URL.

file_get_contents('http://somenotrealurl.com/notrealpage');

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

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
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

心凉 2024-10-13 06:21:03

您需要检查 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');
}

You need to check the 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');
}
年少掌心 2024-10-13 06:21:03

对于 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
}

With such commands in PHP, you can prefix them with an @ to suppress such warnings.

@file_get_contents('http://somenotrealurl.com/notrealpage');

file_get_contents() returns FALSE if a failure occurs, so if you check the returned result against that then you can handle the failure

$pageDocument = @file_get_contents('http://somenotrealurl.com/notrealpage');

if ($pageDocument === false) {
    // Handle error
}
束缚m 2024-10-13 06:21:03

每次使用 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 在本地范围内被覆盖。

Each time you call file_get_contents with an http wrapper, a variable in local scope is created: $http_response_header

This variable contains all HTTP headers. This method is better over get_headers() function since only one request is executed.

Note: 2 different requests can end differently. For example, get_headers() will return 503 and file_get_contents() would return 200. And you would get proper output but would not use it due to 503 error in get_headers() call.

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'];

This aproach also alows you to have track of few request headers stored in different variables since if you use file_get_contents() $http_response_header is overwritten in local scope.

蓝天 2024-10-13 06:21:03

虽然 file_get_contents 非常简洁和方便,但我倾向于使用 Curl 库来实现更好的控制。这是一个例子。

function fetchUrl($uri) {
    $handle = curl_init();

    curl_setopt($handle, CURLOPT_URL, $uri);
    curl_setopt($handle, CURLOPT_POST, false);
    curl_setopt($handle, CURLOPT_BINARYTRANSFER, false);
    curl_setopt($handle, CURLOPT_HEADER, true);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 10);

    $response = curl_exec($handle);
    $hlength  = curl_getinfo($handle, CURLINFO_HEADER_SIZE);
    $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
    $body     = substr($response, $hlength);

    // If HTTP response is not 200, throw exception
    if ($httpCode != 200) {
        throw new Exception($httpCode);
    }

    return $body;
}

$url = 'http://some.host.com/path/to/doc';

try {
    $response = fetchUrl($url);
} catch (Exception $e) {
    error_log('Fetch URL failed: ' . $e->getMessage() . ' for ' . $url);
}

While file_get_contents is very terse and convenient, I tend to favour the Curl library for better control. Here's an example.

function fetchUrl($uri) {
    $handle = curl_init();

    curl_setopt($handle, CURLOPT_URL, $uri);
    curl_setopt($handle, CURLOPT_POST, false);
    curl_setopt($handle, CURLOPT_BINARYTRANSFER, false);
    curl_setopt($handle, CURLOPT_HEADER, true);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 10);

    $response = curl_exec($handle);
    $hlength  = curl_getinfo($handle, CURLINFO_HEADER_SIZE);
    $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
    $body     = substr($response, $hlength);

    // If HTTP response is not 200, throw exception
    if ($httpCode != 200) {
        throw new Exception($httpCode);
    }

    return $body;
}

$url = 'http://some.host.com/path/to/doc';

try {
    $response = fetchUrl($url);
} catch (Exception $e) {
    error_log('Fetch URL failed: ' . $e->getMessage() . ' for ' . $url);
}
别靠近我心 2024-10-13 06:21:03

您可以添加 'ignore_errors' => true 选项:

$options = [
    'http' => [
        'ignore_errors' => true,
        'header' => "Content-Type: application/json\r\n",
    ],
];
$context = stream_context_create($options);
$result = file_get_contents('http://example.com', false, $context);

在这种情况下,您将能够从服务器读取响应。

You may add 'ignore_errors' => true to options:

$options = [
    'http' => [
        'ignore_errors' => true,
        'header' => "Content-Type: application/json\r\n",
    ],
];
$context = stream_context_create($options);
$result = file_get_contents('http://example.com', false, $context);

In that case you will be able to read a response from the server.

多彩岁月 2024-10-13 06:21:03

简单且实用(易于在任何地方使用):

function file_contents_exist($url, $response_code = 200)
{
    $headers = get_headers($url);

    if (substr($headers[0], 9, 3) == $response_code)
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

示例:

$file_path = 'http://www.google.com';

if(file_contents_exist($file_path))
{
    $file = file_get_contents($file_path);
}

Simple and functional (easy to use anywhere):

function file_contents_exist($url, $response_code = 200)
{
    $headers = get_headers($url);

    if (substr($headers[0], 9, 3) == $response_code)
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

Example:

$file_path = 'http://www.google.com';

if(file_contents_exist($file_path))
{
    $file = file_get_contents($file_path);
}
她说她爱他 2024-10-13 06:21:03

为了避免双重请求,如 Orblingynh 你可以结合他们的答案。如果您首先得到有效的回复,请使用它。如果没有找出问题是什么(如果需要)。

$urlToGet = 'http://somenotrealurl.com/notrealpage';
$pageDocument = @file_get_contents($urlToGet);
if ($pageDocument === false) {
     $headers = get_headers($urlToGet);
     $responseCode = substr($headers[0], 9, 3);
     // Handle errors based on response code
     if ($responseCode == '404') {
         //do something, page is missing
     }
     // Etc.
} else {
     // Use $pageDocument, echo or whatever you are doing
}

To avoid double requests as commented by Orbling on the answer of ynh you could combine their answers. If you get a valid response in the first place, use that. If not find out what the problem was (if needed).

$urlToGet = 'http://somenotrealurl.com/notrealpage';
$pageDocument = @file_get_contents($urlToGet);
if ($pageDocument === false) {
     $headers = get_headers($urlToGet);
     $responseCode = substr($headers[0], 9, 3);
     // Handle errors based on response code
     if ($responseCode == '404') {
         //do something, page is missing
     }
     // Etc.
} else {
     // Use $pageDocument, echo or whatever you are doing
}
没有你我更好 2024-10-13 06:21:03
$url = 'https://www.yourdomain.com';

普通

function checkOnline($url) {
    $headers = get_headers($url);
    $code = substr($headers[0], 9, 3);
    if ($code == 200) {
        return true;
    }
    return false;
}

if (checkOnline($url)) {
    // URL is online, do something..
    $getURL = file_get_contents($url);     
} else {
    // URL is offline, throw an error..
}

专业

if (substr(get_headers($url)[0], 9, 3) == 200) {
    // URL is online, do something..
}

Wtf级别

(substr(get_headers($url)[0], 9, 3) == 200) ? echo 'Online' : echo 'Offline';
$url = 'https://www.yourdomain.com';

Normal

function checkOnline($url) {
    $headers = get_headers($url);
    $code = substr($headers[0], 9, 3);
    if ($code == 200) {
        return true;
    }
    return false;
}

if (checkOnline($url)) {
    // URL is online, do something..
    $getURL = file_get_contents($url);     
} else {
    // URL is offline, throw an error..
}

Pro

if (substr(get_headers($url)[0], 9, 3) == 200) {
    // URL is online, do something..
}

Wtf level

(substr(get_headers($url)[0], 9, 3) == 200) ? echo 'Online' : echo 'Offline';
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文