<?php
// 安全配置:允许下载的文件类型(白名单)
$allowed_extensions = ['pdf', 'doc', 'docx', 'txt', 'zip', 'jpg', 'png', 'mp3', 'mp4'];
// 获取请求的文件名
$filename = isset($_GET['file']) ? $_GET['file'] : '';
// 安全检查:防止目录遍历攻击
if (strpos($filename, '..') !== false || strpos($filename, '/') !== false || strpos($filename, '\\') !== false) {
die('非法文件路径');
}
// 检查文件扩展名
$extension = pathinfo($filename, PATHINFO_EXTENSION);
if (!in_array(strtolower($extension), $allowed_extensions)) {
die('不支持的文件类型');
}
// 拼接完整文件路径(根据实际目录结构调整)
$filepath = './downloads/' . $filename;
// 检查文件是否存在
if (!file_exists($filepath)) {
die('文件不存在');
}
// 检查文件是否可读
if (!is_readable($filepath)) {
die('文件不可读');
}
// 设置HTTP头信息
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
// 清空输出缓冲区
ob_clean();
flush();
// 读取文件并输出
readfile($filepath);
exit;
?>
download.php 并上传到服务器downloads 文件夹(与脚本同级)并放入可下载的文件http://yourdomain.com/download.php?file=filename.ext
downloads 目录放在Web根目录外,或通过 .htaccess 限制访问// 增强版示例(伪代码)
session_start();
if (!isset($_SESSION['authenticated']) || !$_SESSION['authenticated']) {
header('Location: login.php');
exit;
}
// 添加下载次数限制
if (downloadCountExceeded($filename)) {
die('下载次数已达上限');
}
// 添加病毒扫描
if (scanFileForMalware($filepath)) {
die('文件包含潜在威胁');
}
此代码提供了基本功能,生产环境使用前应根据具体需求进行安全加固和功能扩展。


