PHP利用CURL判断远程文件是否存在的高效实现
核心实现代码如下所示:
// 用于检测远程文件是否存在的逻辑
function check_remote_file_exists($url)
{
$curl = curl_init($url);
// 配置不获取响应主体数据
curl_setopt($curl, CURLOPT_NOBODY, true);
// 执行网络请求操作
$result = curl_exec($curl);
$found = false;
// 当请求执行未发生错误时
if ($result !== false) {
// 进一步校验HTTP响应状态码是否为200
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($statusCode == 200) {
$found = true;
}
}
curl_close($curl);
return $found;
}
近期在开发一个基于HTML5的音乐播放网站,旨在让iPhone和iPad用户获得流畅体验。前端选用了jQuery插件jplayer,经过定制后效果令人满意。
后端采用PHP语言,定期从百度抓取MP3资源链接。鉴于服务器存储空间有限,仅采集MP3地址而不将文件下载至本地。由于百度MP3的链接路径经常变动,导致直接访问容易失效,因此需要定时校验路径的有效性。起初尝试使用get_headers()方法,但得知其存在性能瓶颈后便弃用,此处仅作简要回顾。以下是get_headers函数的实际输出效果:
具体代码示例如下:
// 默认调用方式
print_r(get_headers("http://www.baidu.com/img/baidu_sylogo1.gif"));
返回结果:
Array
(
[0] => HTTP/1.1 200 OK
[1] => Date: Thu, 02 Jun 2011 02:47:27 GMT
[2] => Server: Apache
[3] => P3P: CP=" OTI DSP COR IVA OUR IND COM "
[4] => Set-Cookie: BAIDUID=7F6A5A2ED03878A7791C89C526966F3A:FG=1; expires=Fri, 01-Jun-12 02:47:27 GMT; max-age=31536000; path=/; domain=.baidu.com; version=1
[5] => Last-Modified: Thu, 20 Jan 2011 07:15:35 GMT
[6] => ETag: "65e-49a41e65933c0"
[7] => Accept-Ranges: bytes
[8] => Content-Length: 1630
[9] => Cache-Control: max-age=315360000
[10] => Expires: Sun, 30 May 2026 02:47:27 GMT
[11] => Connection: Close
[12] => Content-Type: image/gif
)
// 添加参数1后的格式化输出效果
print_r(get_headers("http://www.baidu.com/img/baidu_sylogo1.gif", 1));
返回结果:
Array
(
[0] => HTTP/1.1 200 OK
[Date] => Thu, 02 Jun 2011 02:49:28 GMT
[Server] => Apache
[P3P] => CP=" OTI DSP COR IVA OUR IND COM "
[Set-Cookie] => BAIDUID=4D875812FC482C0ADE4F5C17068849EE:FG=1; expires=Fri, 01-Jun-12 02:49:28 GMT; max-age=31536000; path=/; domain=.baidu.com; version=1
[Last-Modified] => Thu, 20 Jan 2011 07:15:35 GMT
[ETag] => "65e-49a41e65933c0"
[Accept-Ranges] => bytes
[Content-Length] => 1630
[Cache-Control] => max-age=315360000
[Expires] => Sun, 30 May 2026 02:49:28 GMT
[Connection] => Close
[Content-Type] => image/gif
)
虽然get_headers函数功能完善,但考虑到效率问题,不再作为首选方案。相比之下,CURL更为合适,接下来展示CURL的具体实现方式。
相关代码如下:
function check_remote_file_exists($url)
{
$curl = curl_init($url);
// 配置不获取响应主体数据
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET'); // 若不设置此项可能返回403错误,设置后才能正确获取200状态码,具体原因待查
// 执行网络请求操作
$result = curl_exec($curl);
$found = false;
// 当请求执行未发生错误时
if ($result !== false)
{
// 进一步校验HTTP响应状态码是否为200
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($statusCode == 200)
{
$found = true;
}
}
curl_close($curl);
return $found;
}
$exists = check_remote_file_exists('http://www.baidu.com/img/baidu_sylogo1.gif');
echo $exists ? '存在' : '不存在';
$exists = check_remote_file_exists('http://www.baidu.com/test.jpg');
echo $exists ? '存在' : '不存在';