我有一个网址数组(大约1000个网址),我想检查所有网址是否存在。这是我目前的代码:
$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;
}
}
此脚本有效,它会回显所有工作网址,但过程太长(需要几分钟才能完成)。有没有办法更快地做到这一点,还是这样快?也许我可以使用curl_timeout函数来缩短时间?
答案 0 :(得分:3)
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个并发线程。
答案 1 :(得分:0)
对于并行检查,您可以使用multi_curl。它可能很快。这里有一些example。因为它比@eis的例子更复杂。
P.S。还有curl,你可以使用方法HEAD。
答案 2 :(得分: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;
}