【问题标题】:Checking 1000 urls if they exist or not, is there a quick way for this?检查 1000 个网址是否存在,是否有快速的方法?
【发布时间】:2013-03-10 15:15:06
【问题描述】:

我有一个 url 数组(其中有大约 1000 个 url),我想检查它们是否存在。这是我当前的代码:

$south_east_png_endings = array();
for($x=1;$x<=25;$x++) {
    for($y=1;$y<=48;$y++) {
        $south_east_png_endings[] ="${x}s${y}e.png";
    }
}

foreach ($south_east_png_endings as $se){
    $url = 'http://imgs.xkcd.com/clickdrag/'.$se;
    $file_headers = @get_headers($url);
    if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
        // echo 'Does not exist';
    }
    else
    {
        echo $url;
    }
}

此脚本有效,它回显了所有有效的 url,但过程太长(需要几分钟才能完成)。有没有办法更快地做到这一点,或者这是否尽可能快?也许我可以使用 curl_timeout 函数来缩短时间?

【问题讨论】:

标签: php


【解决方案1】:

1) get_headers() 实际上使用 GET 请求,如果您只想知道文件是否存在,则不需要这些请求。改用 HEAD,example from the manual:

<?php
// By default get_headers uses a GET request to fetch the headers. If you
// want to send a HEAD request instead, you can do so using a stream context:
stream_context_set_default(
    array(
        'http' => array(
            'method' => 'HEAD'
        )
    )
);
$headers = get_headers('http://example.com');
?>

2) 由于这些检查可以轻松并行运行,因此您应该使用单独的线程/进程进行检查。但是,如果您在家中执行此操作,您的路由器可能会同时阻塞 1000 个请求,因此您可能需要使用 5-20 个并发线程。

【讨论】:

    【解决方案2】:

    对于并行检查,您可以使用multi_curl。它可能非常快。这里有一些example。因为它比@eis 的例子更复杂。

    附:还可以通过 curl 使用 HEAD 方法。

    【讨论】:

      【解决方案3】:
      function _isUrlexist($url) {
          $flag = false;
          if ($url) {
              $ch = curl_init();
              curl_setopt_array($ch, array(
                  CURLOPT_URL => $url,
                  CURLOPT_RETURNTRANSFER => true,
                  CURLOPT_NOBODY => true,
                  CURLOPT_HEADER => true
                  ));
              curl_exec($ch);
              $info = curl_getinfo($ch, CURLINFO_HTTP_CODE);
              curl_close($ch);
      
              $flag = ($info == 200) ? true : false;
          }
          return $flag;
      }
      

      【讨论】:

      • 虽然此代码可能有助于解决问题,但提供有关 why 和/或 如何 回答问题的附加上下文将显着改善其长期价值。请edit您的回答添加一些解释。特别是,它是遵循 301 和/或 302 重定向,还是仅仅报告这些重定向失败?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-12
      • 2010-11-25
      相关资源
      最近更新 更多