PHP网站文件下载功能实现
在PHP网站中实现文件下载功能需要注意安全性、权限控制和用户体验。以下是完整的实现方案:
基本文件下载实现
php
// download.php// 1. 获取要下载的文件名(应从安全来源获取,如数据库ID)$filename = basename($_GET['file']); // 使用basename防止目录遍历攻击$filepath = 'uploads/' . $filename; // 文件存储路径// 2. 检查文件是否存在if (!file_exists($filepath)) { die("错误:文件不存在");}// 3. 设置适当的头部信息header('Content-Description: File Transfer');header('Content-Type: ' . mime_content_type($filepath));header('Content-Disposition: attachment; filename="'.basename($filepath).'"');header(
' . filesize($filepath));header('Expires: 0');header('Cache-Control: must-revalidate');header('Pragma: public');// 4. 清除输出缓冲区并读取文件ob_clean();flush();readfile($filepath);exit;?>
安全增强版实现
php
// secure_download.php// 1. 配置$allowed_dirs = ['uploads', 'documents']; // 允许下载的目录$max_size = 100 * 1024 * 1024; // 最大允许下载大小(100MB)// 2. 验证请求if (!isset($_GET['file']) || empty($_GET['file'])) { die("未指定下载文件");}// 3. 清理输入$requested_file = basename($_GET['file']);$requested_path = pathinfo($requested_file, PATHINFO_DIRNAME);// 4. 验证目录是否允许if (!in_array($requested_path, $allowed_dirs)) { die("无权访问此
特别声明:以上内容(如有图片或视频亦包括在内)为自媒体平台“网易号”用户上传并发布,本平台仅提供信息存储服务。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.