php 实现防盗链
防盗链的基本概念
防盗链(Hotlink Protection)用于防止其他网站直接引用本网站的图片、视频等资源,避免流量和带宽被恶意消耗。PHP可通过多种方式实现防盗链功能。
检查HTTP Referer
通过检查HTTP请求头中的Referer字段,判断请求是否来自合法域名。若Referer不匹配预设的合法域名,则拒绝访问。
$allowedDomains = ['example.com', 'trusted-site.com'];
$referer = $_SERVER['HTTP_REFERER'] ?? '';
$isValidReferer = false;
foreach ($allowedDomains as $domain) {
if (strpos($referer, $domain) !== false) {
$isValidReferer = true;
break;
}
}
if (!$isValidReferer) {
header('HTTP/1.1 403 Forbidden');
exit('Access denied: Hotlinking not allowed.');
}
生成动态访问令牌
为资源链接添加动态令牌(如时间戳或哈希值),验证请求时检查令牌的有效性。

$secretKey = 'your-secret-key';
$expireTime = time() + 3600; // 1小时有效期
$filePath = '/path/to/resource.jpg';
$token = hash_hmac('sha256', $filePath . $expireTime, $secretKey);
// 生成访问链接
$accessUrl = "download.php?file=" . urlencode($filePath) . "&expire=$expireTime&token=$token";
验证令牌的示例:
$secretKey = 'your-secret-key';
$filePath = $_GET['file'] ?? '';
$expire = $_GET['expire'] ?? 0;
$token = $_GET['token'] ?? '';
if (time() > $expire || $token !== hash_hmac('sha256', $filePath . $expire, $secretKey)) {
header('HTTP/1.1 403 Forbidden');
exit('Invalid or expired access token.');
}
// 允许访问文件
readfile($filePath);
使用.htaccess限制访问
通过Apache的.htaccess文件限制资源访问,仅允许特定域名或IP访问:

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^https://(www\.)?example\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule \.(jpg|png|gif|mp4)$ - [F]
输出图片时添加水印
若检测到非法引用,动态为图片添加水印:
header('Content-Type: image/jpeg');
$image = imagecreatefromjpeg('original.jpg');
$watermark = imagecolorallocate($image, 255, 0, 0);
imagestring($image, 5, 10, 10, 'Stolen Content', $watermark);
imagejpeg($image);
imagedestroy($image);
Nginx防盗链配置
若使用Nginx,可在配置文件中添加规则:
location ~* \.(jpg|png|gif|mp4)$ {
valid_referers none blocked example.com *.example.com;
if ($invalid_referer) {
return 403;
}
}
综合建议
- 结合
Referer检查与动态令牌增强安全性。 - 对敏感资源使用
.htaccess或Nginx规则减少PHP处理压力。 - 动态生成资源链接时限制有效期,避免长期暴露。






