PHP图片防盗链技术实现详解

PHP图片防盗链技术实现详解

在网站开发中,图片资源被其他网站盗用是常见问题。这不仅会增加服务器带宽消耗,还可能影响网站性能。本文将详细介绍几种PHP实现图片防盗链的技术方案,帮助你有效保护图片资源。

一、基于HTTP_REFERER的防盗链

这是最基础的防盗链方法,通过检查请求来源来阻止非法访问。

<?php
// 获取请求来源
$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';

// 允许的域名列表
$allowed_domains = [
    'https://www.mrz2516.com',
    'https://mrz2516.com',
    'http://localhost'
];

// 检查来源是否合法
$is_allowed = false;
foreach ($allowed_domains as $domain) {
    if (strpos($referer, $domain) === 0) {
        $is_allowed = true;
        break;
    }
}

if (!$is_allowed) {
    // 返回403禁止访问或重定向到默认图片
    header('HTTP/1.1 403 Forbidden');
    exit('Access Denied');
}

// 输出图片
$image_path = $_GET['image'];
if (file_exists($image_path)) {
    $image_info = getimagesize($image_path);
    header('Content-Type: ' . $image_info['mime']);
    readfile($image_path);
}
?>
```

二、基于Token的防盗链

通过生成临时访问令牌,限制图片访问的有效期和权限。

<?php
// 生成防盗链Token
function generateImageToken($image_path, $expire_time = 3600) {
    $secret_key = 'key值';
    $timestamp = time();
    $token_data = $image_path . '|' . $timestamp . '|' . $expire_time;
    return hash_hmac('sha256', $token_data, $secret_key) . '|' . $timestamp . '|' . $expire_time;
}

// 验证Token
function verifyImageToken($token, $image_path) {
    $secret_key = 'key值';
    $parts = explode('|', $token);
    
    if (count($parts) !== 3) {
        return false;
    }
    
    list($hash, $timestamp, $expire_time) = $parts;
    $current_time = time();
    
    // 检查是否过期
    if ($current_time - $timestamp > $expire_time) {
        return false;
    }
    
    // 验证哈希
    $token_data = $image_path . '|' . $timestamp . '|' . $expire_time;
    $expected_hash = hash_hmac('sha256', $token_data, $secret_key);
    
    return hash_equals($expected_hash, $hash);
}

// 使用示例
$image_path = $_GET['image'];
$token = $_GET['token'] ?? '';

if (!verifyImageToken($token, $image_path)) {
    header('HTTP/1.1 403 Forbidden');
    exit('Invalid or expired token');
}

// 输出图片
if (file_exists($image_path)) {
    $image_info = getimagesize($image_path);
    header('Content-Type: ' . $image_info['mime']);
    readfile($image_path);
}
?>

三、基于Session的防盗链

利用PHP Session机制,确保只有通过正常页面访问才能获取图片。

<?php
session_start();

// 在正常页面中设置访问标记
function setImageAccess($image_id) {
    $_SESSION['image_access'][$image_id] = time();
}

// 验证图片访问权限
function checkImageAccess($image_id, $timeout = 300) {
    if (!isset($_SESSION['image_access'][$image_id])) {
        return false;
    }
    
    $access_time = $_SESSION['image_access'][$image_id];
    if (time() - $access_time > $timeout) {
        unset($_SESSION['image_access'][$image_id]);
        return false;
    }
    
    return true;
}

// 图片访问脚本
$image_id = $_GET['id'] ?? '';
if (!checkImageAccess($image_id)) {
    header('HTTP/1.1 403 Forbidden');
    exit('Access Denied');
}

// 根据ID获取图片路径并输出
$image_path = getImagePathById($image_id);
if ($image_path && file_exists($image_path)) {
    $image_info = getimagesize($image_path);
    header('Content-Type: ' . $image_info['mime']);
    readfile($image_path);
}
?>

四、基于IP白名单的防盗链

限制只有特定IP地址可以访问图片资源。

<?php
// 获取客户端IP
function getClientIP() {
    $ip_keys = ['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR'];
    
    foreach ($ip_keys as $key) {
        if (array_key_exists($key, $_SERVER) === true) {
            foreach (explode(',', $_SERVER[$key]) as $ip) {
                $ip = trim($ip);
                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {
                    return $ip;
                }
            }
        }
    }
    
    return $_SERVER['REMOTE_ADDR'] ?? '';
}

// 检查IP是否在白名单中
function isIPAllowed($client_ip) {
    $allowed_ips = [
        '192.168.1.100',
        '10.0.0.50',
        // 添加更多允许的IP
    ];
    
    return in_array($client_ip, $allowed_ips);
}

$client_ip = getClientIP();
if (!isIPAllowed($client_ip)) {
    header('HTTP/1.1 403 Forbidden');
    exit('IP not allowed');
}

// 输出图片
$image_path = $_GET['image'];
if (file_exists($image_path)) {
    $image_info = getimagesize($image_path);
    header('Content-Type: ' . $image_info['mime']);
    readfile($image_path);
}
?>

五、综合防盗链方案

综合防盗技术

<?php
class ImageProtection {
    private $secret_key;
    private $allowed_domains;
    private $cache_time;
    
    public function __construct($secret_key, $allowed_domains = [], $cache_time = 3600) {
        $this->secret_key = $secret_key;
        $this->allowed_domains = $allowed_domains;
        $this->cache_time = $cache_time;
    }
    
    // 检查HTTP_REFERER
    public function checkReferer() {
        $referer = $_SERVER['HTTP_REFERER'] ?? '';
        
        if (empty($referer)) {
            return false;
        }
        
        foreach ($this->allowed_domains as $domain) {
            if (strpos($referer, $domain) === 0) {
                return true;
            }
        }
        
        return false;
    }
    
    // 生成访问令牌
    public function generateToken($image_path) {
        $timestamp = time();
        $data = $image_path . '|' . $timestamp;
        return hash_hmac('sha256', $data, $this->secret_key) . '|' . $timestamp;
    }
    
    // 验证令牌
    public function verifyToken($token, $image_path) {
        $parts = explode('|', $token);
        if (count($parts) !== 2) {
            return false;
        }
        
        list($hash, $timestamp) = $parts;
        $current_time = time();
        
        if ($current_time - $timestamp > $this->cache_time) {
            return false;
        }
        
        $data = $image_path . '|' . $timestamp;
        $expected_hash = hash_hmac('sha256', $data, $this->secret_key);
        
        return hash_equals($expected_hash, $hash);
    }
    
    // 输出图片
    public function serveImage($image_path) {
        if (!file_exists($image_path)) {
            header('HTTP/1.1 404 Not Found');
            exit('Image not found');
        }
        
        $image_info = getimagesize($image_path);
        header('Content-Type: ' . $image_info['mime']);
        header('Cache-Control: private, max-age=3600');
        readfile($image_path);
    }
}

// 使用示例
$protection = new ImageProtection(
    'key值',
    ['https://www.mrz2516.com', 'https://mrz2516.com']
);

$image_path = $_GET['image'] ?? '';
$token = $_GET['token'] ?? '';

// 检查访问权限
if (!$protection->checkReferer() && !$protection->verifyToken($token, $image_path)) {
    header('HTTP/1.1 403 Forbidden');
    exit('Access Denied');
}

$protection->serveImage($image_path);
?>
```

六、.htaccess防盗链配置

除了PHP代码,还可以通过Apache的.htaccess文件实现防盗链:

```apache
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?mrz2516.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [F]
```

七、实践建议

  1. 多层防护:结合多种防盗链技术,提高安全性
  2. 性能优化:使用缓存机制,避免重复验证
  3. 用户体验:提供友好的错误页面,而不是直接拒绝访问
  4. 监控日志:记录防盗链事件,便于分析和优化
  5. 定期更新:及时更新防盗链策略,应对新的攻击方式
© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容