php实现下载功能
PHP实现文件下载功能
使用PHP实现文件下载功能可以通过设置HTTP头信息控制浏览器行为,以下是几种常见实现方式:

基础下载方法
$file_path = '/path/to/file.pdf';
$file_name = 'document.pdf';
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path));
readfile($file_path);
exit;
大文件分块下载
对于大文件下载,建议使用分块读取方式避免内存问题:

$file = fopen($file_path, 'rb');
while(!feof($file)) {
print(fread($file, 1024*8));
ob_flush();
flush();
}
fclose($file);
动态生成内容下载
如需下载动态生成的内容(如CSV数据):
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="data.csv"');
$output = fopen('php://output', 'w');
fputcsv($output, ['ID', 'Name', 'Email']);
fputcsv($output, [1, 'John', 'john@example.com']);
fclose($output);
安全注意事项
- 验证文件路径防止目录遍历攻击
- 限制下载目录范围
- 对用户权限进行检查
- 记录下载日志
// 安全示例
$base_dir = '/safe/download/dir/';
$requested_file = $_GET['file'];
$real_path = realpath($base_dir . $requested_file);
if(strpos($real_path, $base_dir) === 0 && file_exists($real_path)) {
// 安全下载逻辑
}
常见问题处理
下载中文文件名时可能出现乱码,需要额外处理:
$encoded_name = rawurlencode($file_name);
header('Content-Disposition: attachment; filename*=UTF-8\'\'' . $encoded_name);
以上方法涵盖了PHP实现下载功能的主要场景,可根据实际需求选择适合的方案。






