Feb
21
2024
使用 php 检查一个通过 http 协议访问的网络文件是否存在
作者:
绝缘体.. 发布:
2024-02-21 07:47 分类:
未分类 阅读:
抢沙发
使用 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_USERAGENT, 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'); // 模拟浏览器
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;
}
微信扫一扫,打赏作者吧~