图片防盗链的核心原理:验证图片请求的域名来源,只允许本站加载图片,拒绝外部未授权网站引用图片地址,以达到防盗链的目的。
浏览器请求图片时,会执行HTTP_REFERER请求头,记录从哪个页面发起请求,用程序判断读取该来源的地址,是否是合法域名,是则输出图片,否则返回禁止图片或403。
方案1:基础防盗链
img.php
<?php
// 允许访问的域名
$allow_hosts = [
'localhost', // 本地测试
'yourname.com', // 你的主域名
'www.yourname.com' // 你的www域名
];
// 图片真实目录
$image_dir = __DIR__ . '/uploads/';
// 防盗链默认图片
$forbidden_img = __DIR__ . '/forbidden.png';
// 获取请求来源
$referer = $_SERVER['HTTP_REFERER'] ?? '';
// 验证来源是否合法
$is_allow = false;
if (!empty($referer)) {
$referer_host = parse_url($referer, PHP_URL_HOST);
$is_allow = in_array($referer_host, $allow_hosts);
}
// 获取访问图片文件名
$filename = $_GET['file'] ?? '';
$filename = basename($filename); // 只保留文件名
$real_file = $image_dir . $filename;
// 输出哪张图片
if ($is_allow && file_exists($real_file)) {
// 输出真实图片
$output_file = $real_file;
} else {
// 输出防盗链提示图
$output_file = $forbidden_img;
}
// 输出图片
$mime = mime_content_type($output_file);
header("Content-Type: $mime");
header("Content-Length: " . filesize($output_file));
readfile($output_file);
exit;
?>
使用方法
<!-- 正常写法 -->
<img src="/uploads/1.jpg">
<!-- 防盗链写法 -->
<img src="/img.php?file=1.jpg">
方案2:推荐生产环境
img.php
<?php
// 允许访问的域名
$allow_hosts = [
'localhost', // 本地测试
'yourname.com', // 你的主域名
'www.yourname.com' // 你的www域名
];
// 图片真实目录
$image_dir = __DIR__ . '/uploads/';
// 防盗链默认图片
$forbidden_img = __DIR__ . '/forbidden.png';
// 强制校验REFERER
if (empty($_SERVER['HTTP_REFERER'])) {
show_forbidden_img($forbidden_img);
}
$referer = $_SERVER['HTTP_REFERER'];
$referer_host = parse_url($referer, PHP_URL_HOST);
// 域名白名单验证
if (!in_array($referer_host, $allow_hosts)) {
show_forbidden_img($forbidden_img);
}
// 安全获取文件名
$filename = basename($_GET['file'] ?? '');
$real_file = $image_dir . $filename;
// 判断输出图片
if (file_exists($real_file)) {
output_image($real_file);
} else {
show_forbidden_img($forbidden_img);
}
// 输出禁止图片
function show_forbidden_img($img) {
output_image($img);
exit;
}
// 输出图片函数
function output_image($path) {
$mime = mime_content_type($path);
header("Content-Type: $mime");
header("Content-Length: " . filesize($path));
readfile($path);
}
?>
方案3:Nginx防盗链,更方便
location ~* \.(jpg|jpeg|png|gif|bmp)$ {
valid_referers none blocked server_names yourname.com www.yourname.com;
if ($invalid_referer) {
# 返回盗链提示图
rewrite ^ /forbidden.png last;
# 返回403
# return 403;
}
expires 30d; # 缓存30天
} 本站原创内容,转载请注明来源:https://www.liutonghui.com/17
评论列表(0条)
暂无评论