php实现文件的下载
使用 header() 函数实现文件下载
通过设置 HTTP 头信息强制浏览器下载文件而非直接显示。需指定 Content-Type 为 application/octet-stream,并设置 Content-Disposition 为附件形式。
$file_path = '/path/to/file.pdf';
$file_name = 'download.pdf';
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $file_name . '"');
header('Content-Length: ' . filesize($file_path));
readfile($file_path);
exit;
处理大文件的分块下载
对于大文件,使用 fread() 分块读取并输出,避免内存溢出。
$file_path = '/path/to/large_file.zip';
$chunk_size = 1024 * 1024; // 1MB per chunk
$handle = fopen($file_path, 'rb');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
ob_flush();
flush();
}
fclose($handle);
exit;
动态生成文件并下载
适用于临时生成 CSV、Excel 等文件后直接提供下载。
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="data.csv"');
$output = fopen('php://output', 'w');
fputcsv($output, ['Name', 'Email']); // 写入表头
fputcsv($output, ['Alice', 'alice@example.com']); // 写入数据
fclose($output);
exit;
安全注意事项
- 验证文件路径:防止目录遍历攻击,确保用户无法访问非授权文件。
$base_dir = '/safe/directory/'; $requested_file = $_GET['file']; if (strpos(realpath($base_dir . $requested_file), $base_dir) === 0) { // 安全路径 } - 限制下载频率:防止恶意刷流量,可通过会话或 IP 记录控制下载次数。
使用 X-Sendfile 提升性能(需服务器支持)
通过让服务器直接处理文件传输,减少 PHP 进程的资源占用。

header('X-Sendfile: /path/to/file.zip');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="file.zip"');
exit;
以上方法覆盖了从简单下载到高性能处理的常见场景,可根据实际需求选择。






