生成带有效期的临时下载链接需包含文件路径、过期时间戳和签名,通过校验签名与时间防止滥用。1. 生成时使用 secret key 对 path + expires 生成签名,如 generateSignedUrl 函数所示;2. 下载时在 download.php 中验证签名是否匹配(用 hash_equals 防时序攻击)且未过期;3. 安全校验包括限制路径、使用 HTTPS、记录日志,并可扩展绑定 IP 或用户增强安全。核心是签名一致、时间有效、密钥保密。

生成带有效期的临时下载链接,核心是通过签名和时间戳校验来防止链接被滥用。PHP 实现这一功能的关键在于:在生成链接时加入过期时间与签名,访问时验证签名和是否过期。这种方式常用于对象存储(如阿里云OSS、AWS S3)的私有文件分享。
1. 临时链接的生成逻辑
临时下载链接通常包含原始资源路径、过期时间戳和签名串。用户访问时,服务端重新计算签名并比对,同时检查时间是否过期。
基本参数包括:
- path:要下载的文件路径
- expires:链接过期的时间戳(Unix timestamp)
- signature:基于 secret key 对 path + expires 生成的签名
示例生成函数:
立即学习“PHP免费学习笔记(深入)”;
function generateSignedUrl($filePath, $expireSeconds = 3600, $secretKey) {
$expires = time() + $expireSeconds;
$signature = md5($filePath . $expires . $secretKey);
$params = http_build_query([
'path' => $filePath,
'expires' => $expires,
'signature' => $signature
]);
return 'download.php?' . $params;
}
调用示例:
$secret = 'your_secret_key_here';
$url = generateSignedUrl('/files/report.pdf', 1800, $secret); // 30分钟有效
echo $url;
// 输出类似:download.php?path=%2Ffiles%2Freport.pdf&expires=1712345678&signature=a1b2c3d4...
2. 下载脚本中的签名与时间校验
在接收请求的 download.php 中,必须严格校验签名和时间,确保链接未过期且未被篡改。
$filePath = $_GET['path'] ?? '';
$expires = (int)($_GET['expires'] ?? 0);
$signature = $_GET['signature'] ?? '';
if (empty($filePath) || empty($signature)) {
http_response_code(400);
die('Invalid request');
}
if (time() > $expires) {
http_response_code(410);
die('Link expired');
}
$expectedSignature = md5($filePath . $expires . 'your_secret_key_here');
if (!hash_equals($expectedSignature, $signature)) {
http_response_code(403);
die('Invalid signature');
}
if (file_exists($filePath) && is_readable($filePath)) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
readfile($filePath);
} else {
http_response_code(404);
die('File not found');
}
注意: 使用 hash_equals() 防止时序攻击,确保字符串比较安全。
3. 安全建议与优化点
- 使用强密钥:secret key 应足够长且随机,避免被暴力破解
- 限制路径访问:对 $filePath 做白名单或目录限制,防止路径穿越(如 ../../)
- 日志记录:记录每次下载请求,便于审计和排查异常
- 支持 HTTPS:防止链接在传输中被截获
- 可扩展参数:可加入 user_id、ip 绑定等进一步增强安全性
基本上就这些。只要签名算法一致、时间校验严格、密钥保密,就能有效实现防盗链的临时下载功能。不复杂但容易忽略细节,比如时间同步和 hash_equals 的使用。











