当前位置:首页>技术记录>PHP图片代理缓存 永久缓存在服务器

PHP图片代理缓存 永久缓存在服务器

用户访问地址,图片没有缓存的会自动缓存,缓存过的图片如果被缓存地址已经失效了,优先读取缓存。

<?php
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/' . md5($url); // 根据图片地址创建缓存文件夹
    
    if (!file_exists($cacheDir)) {
        mkdir($cacheDir, 0777, true); // 创建缓存文件夹
    }
    
    $cachedImagePath = $cacheDir . '/cached_image.'.$ext; // 缓存图片路径
    
    if (file_exists($cachedImagePath)) {
        // 返回缓存图片
        readfile($cachedImagePath);
    } else {
        // 保存原始图片内容到缓存文件夹
        file_put_contents($cachedImagePath, $data);
        
        // 输出原始图片
        echo $data;
    }
}
?>

保存为img.php文件。

如何使用:

https://域名/img.php?url=地址

案例:

https://api.photo8.site/imgdl/img.php?url=https://photo.tuchong.com/27367140/l/1142111964.webp

也可以直接插入图片。

PHP图片代理缓存 永久缓存在服务器

可以用于一些采集场景,只需要替换图片地址即可。

请使用上方代码自行搭建,本站图片代理30天自动清除缓存。

个人中心
搜索