1

我有一个 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 函数来缩短时间?

4

3 回答 3

3

1) get_headers() 实际上使用 GET 请求,如果您只想知道文件是否存在,则不需要这些请求。改用 HEAD,手册中的示例

<?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 个并发线程。

于 2013-03-21T07:51:38.423 回答
0

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

PS 同样使用 curl 您可以使用 HEAD 方法的技巧。

于 2013-03-21T08:20:39.417 回答
0
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;
}
于 2016-07-08T11:26:01.033 回答