php实现下载
PHP实现文件下载
使用PHP实现文件下载可以通过设置HTTP头部信息强制浏览器下载文件而非直接打开。以下是几种常见的方法:
方法一:直接输出文件内容
$file_path = 'path/to/your/file.pdf';
$file_name = basename($file_path);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $file_name . '"');
header('Content-Length: ' . filesize($file_path));
readfile($file_path);
exit;
方法二:处理大文件分块下载
对于大文件,可以分块读取避免内存问题:
$file_path = 'large_file.zip';
$file_name = basename($file_path);
$chunk_size = 1024 * 1024; // 1MB chunks
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $file_name . '"');
header('Content-Length: ' . filesize($file_path));
$handle = fopen($file_path, 'rb');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
ob_flush();
flush();
}
fclose($handle);
exit;
方法三:动态生成内容下载
如果需要下载动态生成的内容(如CSV数据):
$data = "Name,Email,Phone\nJohn,john@example.com,123456789";
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Content-Length: ' . strlen($data));
echo $data;
exit;
注意事项
- 确保文件路径正确且有读取权限
- 在发送头部前不能有任何输出(包括空格和空行)
- 对于敏感文件,建议存储在web目录外并通过PHP脚本控制访问
- 添加安全验证防止未授权下载
安全增强示例
// 验证用户权限
if (!user_has_permission()) {
die('Access denied');
}
$file_path = '/secure/path/to/file.pdf';
// 进一步验证文件是否存在且可读





