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

生成带有效期的临时下载链接,核心是通过签名和时间戳校验来防止链接被滥用。PHP 实现这一功能的关键在于:在生成链接时加入过期时间与签名,访问时验证签名和是否过期。这种方式常用于对象存储(如阿里云OSS、AWS S3)的私有文件分享。
临时下载链接通常包含原始资源路径、过期时间戳和签名串。用户访问时,服务端重新计算签名并比对,同时检查时间是否过期。
基本参数包括:
示例生成函数:
立即学习“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...
在接收请求的 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() 防止时序攻击,确保字符串比较安全。
基本上就这些。只要签名算法一致、时间校验严格、密钥保密,就能有效实现防盗链的临时下载功能。不复杂但容易忽略细节,比如时间同步和 hash_equals 的使用。
以上就是php如何生成带有效期的临时下载链接_php链接签名与时间戳校验防盗链实现的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号