PHP使用pathinfo无法获取图片URL扩展名,求解决方法
解决Googleusercontent图片URL无法用
pathinfo获取扩展名的问题 我来帮你搞定这个问题~你遇到的情况很典型:这个Googleusercontent的图片URL本身并没有携带传统的文件扩展名(比如.jpg、.png),末尾的=w300只是用来控制图片缩放的参数,所以pathinfo自然没办法从这个URL里提取到有效的扩展名。下面给你几个实用的解决办法:
方法1:通过HTTP响应头的Content-Type推导扩展名
这个方法不需要下载完整图片,只请求响应头就能拿到图片类型,再映射成对应的扩展名:
$url = 'https://lh3.googleusercontent.com/-4T303dPCnp0ZnkzQjSIjeB7k8L_DiQglhUgNqXM-OkeLQXoNwwFnzM1MoFjJGw7DGI=w300'; // 初始化cURL请求,仅获取响应头 $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_NOBODY, true); // 不下载图片内容,只拿头部信息 $response = curl_exec($ch); curl_close($ch); // 解析Content-Type字段 if (preg_match('/Content-Type: image\/(\w+)/i', $response, $matches)) { $ext = $matches[1]; // 处理jpeg转jpg的常见兼容情况 if ($ext === 'jpeg') { $ext = 'jpg'; } echo "图片扩展名:$ext"; } else { echo "无法获取图片类型信息"; }
方法2:读取本地图片文件的二进制签名判断格式(更可靠)
如果已经把图片下载到本地,这个方法更准确——每种图片格式都有独特的二进制开头签名,不受响应头可能出错的影响:
function getImageExtension($filePath) { // 读取文件前8个字节的二进制内容 $file = fopen($filePath, 'rb'); $bytes = fread($file, 8); fclose($file); $hexBytes = bin2hex($bytes); // 匹配常见图片格式的二进制签名 $signatures = [ 'ffd8ffe0' => 'jpg', 'ffd8ffe1' => 'jpg', '89504e47' => 'png', '47494638' => 'gif', '52494646' => 'webp' ]; foreach ($signatures as $sig => $ext) { if (str_starts_with($hexBytes, $sig)) { return $ext; } } return false; } // 假设图片已经保存到这个路径 $filePath = $destinationPath . $filename; $ext = getImageExtension($filePath); if ($ext) { echo "图片扩展名:$ext"; } else { echo "无法识别图片格式"; }
方法3:下载图片时直接指定正确的扩展名
如果是在下载图片的流程里,可以先获取扩展名,再给文件加上正确的后缀,这样之后用pathinfo就能正常获取了:
$url = 'https://lh3.googleusercontent.com/-4T303dPCnp0ZnkzQjSIjeB7k8L_DiQglhUgNqXM-OkeLQXoNwwFnzM1MoFjJGw7DGI=w300'; $destinationPath = './your-save-path/'; // 先获取Content-Type确定扩展名 $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_NOBODY, true); $response = curl_exec($ch); curl_close($ch); $ext = 'jpg'; // 设置默认扩展名 if (preg_match('/Content-Type: image\/(\w+)/i', $response, $matches)) { $ext = $matches[1]; $ext = $ext === 'jpeg' ? 'jpg' : $ext; } // 生成带扩展名的文件名 $filename = uniqid() . '.' . $ext; $fullPath = $destinationPath . $filename; // 下载并保存图片 file_put_contents($fullPath, file_get_contents($url)); // 现在用pathinfo就能正常拿到扩展名了 $extFromPath = pathinfo($fullPath, PATHINFO_EXTENSION); echo $extFromPath;
内容的提问来源于stack exchange,提问作者Mokariya Sanjay
相关产品推荐
相关产品推荐

