PHP使用CURL获取远程图片体积大小的方法
直接参考以下代码示例,逻辑清晰易懂。 复制代码 代码如下: //调用示例 echo remote_filesize($url,$user='',$pw=''); $url = "http://www.aa.com/librarys/images/random/rand_11.jpg"; //请替换为实际的图片地址 echo remote_filesize($url,$user='',$pw='');
function remote_filesize($uri,$user='',$pw='') { // 开启输出缓冲 ob_start(); // 初始化CURL并指定目标URI $ch = curl_init($uri); // 确保获取头部信息 curl_setopt($ch, CURLOPT_HEADER, 1); // 设置为HTTP HEAD请求模式 curl_setopt($ch, CURLOPT_NOBODY, 1); // 如需身份验证,在此配置 if (!empty($user) && !empty($pw)) { $headers = array('Authorization: Basic ' . base64_encode($user.':'.$pw)); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); } $okay = curl_exec($ch); curl_close($ch); // 获取输出缓冲区内容 $head = ob_get_contents(); // 清理输出缓冲区并恢复之前的缓冲设置 ob_end_clean(); // 从HTTP头部的Content-Length字段提取数值 $regex = '/Content-Length:\s([0-9].+?)\s/'; $count = preg_match($regex, $head, $matches); // 若存在Content-Length字段,其值将存入$matches[1] if (isset($matches[1])) { $size = $matches[1]; } else { $size = 'unknown'; } $last_mb = round($size/(1024*1024),3); $last_kb = round($size/1024,3); return $last_kb . 'KB / ' . $last_mb.' MB'; } 该函数的核心思路是利用CURL发起请求并将响应存入缓冲区,随后通过正则表达式提取图片的Content-Length信息即可完成体积计算。