使用 php 检查一个通过 http 协议访问的网络文件是否存在。
/**
* 检查一个通过 http 协议访问的网络文件是否存在
* @param string $url
* @return bool
*/
function checkIfHttpFileExists($url): bool {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true); // 只检查头部信息,不下载整个文件
curl_setopt($ch, CURLOPT_FAILONERROR, true); // 在HTTP错误时返回false
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回结果而不是直接输出
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 跟随重定向
curl_setopt($ch, CURLOPT_TIMEOUT, 10); // 设置超时时间
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// 200表示成功,404表示文件不存在
return $httpCode === 200;
}