PHP站点外链图片无法显示怎么办?
管理员
2025-08-27
66
技术文档
PHP站点外链图片无法显示怎么办?
在网站用了外部图片时,部分图片可能有防外链功能,导致图片无法显示。根据以下方法解决:
在根目录创建img.php文件
将以下代码写入文件中
<?php
$url = $_GET["url"];
$url = str_replace("https:/","https://",$url);
$dir = pathinfo($url); //获取图片信息
$host = $dir['dirname']; //图片dirname
$refer = $host.'/';
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_REFERER, $refer);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
$ext = strtolower(substr(strrchr($img,'.'),1,10));
$types = array(
'gif'=>'image/gif',
'jpeg'=>'image/jpeg',
'jpg'=>'image/jpeg',
'jpe'=>'image/jpeg',
'png'=>'image/png',
);
$type = $types[$ext] ? $types[$ext] : 'image/jpeg';
header("Content-type: ".$type);
echo $data;
然后外链图片地址前面加上/img.php?url=图片地址
就可以解决了