feat: 添加图像缓存系统以优化远程图片加载性能
新增img.php文件,旧版本文件,一个开源项目的原始文件。
This commit is contained in:
parent
5bbadf3671
commit
192fc2f45c
69
img.php
Normal file
69
img.php
Normal file
@ -0,0 +1,69 @@
|
|||||||
|
<?php
|
||||||
|
/*
|
||||||
|
'图像缓存系统'
|
||||||
|
使用方式传入远程图片地址例如:
|
||||||
|
/img.php?url=https://www.baidu.com/img/flexible/logo/pc/result.png
|
||||||
|
*/
|
||||||
|
error_reporting(E_ERROR | E_PARSE);
|
||||||
|
@ini_set('max_execution_time', '0');
|
||||||
|
@ini_set("memory_limit",'-1');
|
||||||
|
$url = $_GET["url"];
|
||||||
|
if (!empty($url) && substr($url, 0, 4) == 'http') {
|
||||||
|
$dir = pathinfo($url);
|
||||||
|
$host = $dir['dirname'];
|
||||||
|
$ext = $dir['extension'];
|
||||||
|
$refer = $host.'/';
|
||||||
|
$ch = curl_init($url);
|
||||||
|
curl_setopt($ch, CURLOPT_REFERER, $refer);
|
||||||
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
|
||||||
|
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
|
||||||
|
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
|
||||||
|
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
|
||||||
|
curl_setopt($ch, CURLOPT_HEADER, 0);
|
||||||
|
curl_setopt($ch, CURLOPT_POST, 0);
|
||||||
|
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
|
||||||
|
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
|
||||||
|
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
|
||||||
|
$data = @curl_exec($ch);
|
||||||
|
curl_close($ch);
|
||||||
|
|
||||||
|
$types = array(
|
||||||
|
'gif' => 'image/gif',
|
||||||
|
'jpeg' => 'image/jpeg',
|
||||||
|
'jpg' => 'image/jpeg',
|
||||||
|
'jpe' => 'image/jpeg',
|
||||||
|
'png' => 'image/png',
|
||||||
|
'webp' => 'image/webp',
|
||||||
|
);
|
||||||
|
$type = $types[$ext] ? $types[$ext] : 'image/jpeg';
|
||||||
|
|
||||||
|
header("Content-type: ".$type);
|
||||||
|
|
||||||
|
// 缓存图片
|
||||||
|
$cacheDir = 'cache'; // 缓存文件夹
|
||||||
|
|
||||||
|
// 根据被缓存的网址创建文件夹
|
||||||
|
$parsedUrl = parse_url($url);
|
||||||
|
$domain = $parsedUrl['host'];
|
||||||
|
$cacheSubDir = $cacheDir . '/' . $domain;
|
||||||
|
if (!file_exists($cacheSubDir)) {
|
||||||
|
mkdir($cacheSubDir, 0777, true); // 创建缓存子文件夹
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取原始图片名称
|
||||||
|
$imageName = basename($url);
|
||||||
|
|
||||||
|
$cachedImagePath = $cacheSubDir . '/' . $imageName; // 缓存图片路径
|
||||||
|
|
||||||
|
if (file_exists($cachedImagePath)) {
|
||||||
|
// 返回缓存图片
|
||||||
|
readfile($cachedImagePath);
|
||||||
|
} else {
|
||||||
|
// 保存原始图片内容到缓存文件夹
|
||||||
|
file_put_contents($cachedImagePath, $data);
|
||||||
|
|
||||||
|
// 输出原始图片
|
||||||
|
echo $data;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
?>
|
Loading…
x
Reference in New Issue
Block a user