【问题标题】:How to handle get_headers() function if URL doesn't exist如果 URL 不存在,如何处理 get_headers() 函数
【发布时间】:2018-03-20 19:14:43
【问题描述】:

例如,在使用函数get_headers() 时,如果我写了

get_headers("www.websitedoesntexist.com");

我收到以下错误

警告:get_headers():php_network_getaddresses:getaddrinfo 失败: 没有这样的主机是已知的警告: get_headers(www.websitedoesntexist.com):无法打开流: php_network_getaddresses: getaddrinfo failed: No such host is known

我想知道如何处理这些问题,比如

if (isset(get_headers("www.websitedoesntexist.com"))) {
    echo "URL Exists";
}

【问题讨论】:

标签: php


【解决方案1】:

抑制 get_headers() 函数的错误。将 get_headers 分配给一个变量。然后检查该变量的布尔值。

 $file_headers = @get_headers("www.websitedoesntexist.com");
 if(!$file_headers) {
     $exists = false;
 }
 else {
     $exists = true;
 }

编辑:

基于 cmets,有关使用 curl 的更好的长期解决方案,请参阅https://stackoverflow.com/a/36743670/4374801

【讨论】:

  • 解决了,我之前试过这样做,但是函数开头没有@@是如何改变一切的?
  • 它抑制函数上的错误。但是,请小心使用它。您确实希望确保处理错误情况。它只是让您控制处理错误。
  • 您只是忽略了这里的警告和注意事项,并没有解决问题:)
  • @AXAI 例如,假设有一天您的传出连接出现问题。该函数将失败,不一定是因为 URL 失败,这将使调试变得很糟糕。最好检查发生的情况并进行相应处理。
  • 在这种情况下,为什么不使用curl 来代替呢?你知道忽略错误是一种不好的做法!
【解决方案2】:

来自 PHP 手册:

返回带有标头的索引或关联数组,失败时返回 FALSE。

这意味着您可以针对 FALSE 进行测试。

阅读更多:http://php.net/manual/en/function.get-headers.php

编辑

如果你只想检查 URL 是否存在,而不是抑制错误,我建议你使用 curl,这样一个简单的函数就可以完成这项工作:

function url_exists($url) {
    if (!$fp = curl_init($url)) {
        return false;
    } 
    return true;
}

【讨论】:

  • 我已经尝试过if (get_headers("www.websitedoesntexist.com" != FALSE),但仍然给我带来了致命的问题。
  • empty 怎么样?像这样:if (empty(get_headers("www.websitedoesntexist.com"))) { echo 'Oh man!'; }
  • 相同,给出fatal error,之后条件echo有效,但在长fatal error报告之后
  • 我试过了,它对我有用,我得到的唯一警告是因为我没有将我的 php.ini 配置为 allow_url_fopen = On
  • 我的allow_url_fopen 也是On,我对curl 不太了解的问题,它会使用更多带宽然后只是抑制错误吗?还有什么是$fp,因为它是未定义的?
【解决方案3】:

如果你想在php中检查url是否存在,只需编写this.testing purpose

$array = get_headers('url');
$string = $array[0];
    if (strpos($string, "200")) {
    echo "thats cool dude";
} else {
    echo "Bad request";
} 

【讨论】:

    猜你喜欢
    • 2010-12-05
    • 1970-01-01
    • 1970-01-01
    • 2012-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多