为了快速的判断图片是否存在,一个一个的访问效率太低,可以通过curl_multi_add_handle()函数将多个 cURL 句柄添加多个 URL,然后使用 cURL 多处理器执行它们,这样就可以提高检测效率了。
以下是实现代码:
//批量快速检测在线图片是否存在
function checkImages($urls) {
$mh = curl_multi_init();
$handles = array();
$results = array();
// 遍历 URL 列表,为每个 URL 创建一个 cURL 句柄
foreach ($urls as $url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2); // 使用 HTTP/2
if (strpos($url, "https://") === 0) { // 判断是否为 HTTPS,如果是,则禁用 SSL 验证
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
}
curl_multi_add_handle($mh, $ch);
$handles[] = $ch;
}
// 执行 cURL 句柄,直到所有句柄都执行完毕
$running = null;
do {
curl_multi_exec($mh, $running);
} while ($running > 0);
// 从每个 cURL 句柄中读取结果,保存到结果数组中
foreach ($handles as $i => $ch) {
$url = $urls[$i];
$info = curl_getinfo($ch);
$code = $info['http_code'];
if ($code == 200) {
$results[$url] = true;
} else {
$results[$url] = false;
}
curl_multi_remove_handle($mh, $ch);
curl_close($ch);
}
curl_multi_close($mh);
return $results;
}
$urls = array(
'http://example.com/image1.jpg',
'http://example.com/image2.jpg',
'http://example.com/image3.jpg',
);
$results = checkImages($urls);
foreach ($results as $url => $code) {
if ($code == 200) {
echo "$url exists.<br>";
} else {
echo "$url does not exist.<br>";
}
}