php实现文件的下载
使用 header() 函数实现文件下载
通过设置 HTTP 头部信息,强制浏览器下载文件而非直接打开。核心是 Content-Disposition 和 Content-Type 头部。
$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('Content-Length: ' . filesize($file_path));
readfile($file_path);
exit;
处理大文件下载
对于大文件,使用分块读取避免内存耗尽:

$chunk_size = 1024 * 1024; // 1MB chunks
$handle = fopen($file_path, 'rb');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
ob_flush();
flush();
}
fclose($handle);
安全下载注意事项
验证文件路径防止目录遍历攻击:

$base_dir = '/secure/downloads/';
$requested_file = $_GET['file'];
$real_path = realpath($base_dir . $requested_file);
if ($real_path && strpos($real_path, $base_dir) === 0 && is_file($real_path)) {
// 安全下载逻辑
} else {
die('Invalid file requested');
}
动态生成文件下载
对于动态生成的内容(如 CSV),直接输出到下载流:
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="data.csv"');
$output = fopen('php://output', 'w');
fputcsv($output, ['Column1', 'Column2']);
// 添加数据行...
fclose($output);
断点续传支持
实现 Range 请求支持,允许暂停后继续下载:
if (isset($_SERVER['HTTP_RANGE'])) {
// 解析Range头并实现分片发送
} else {
// 普通完整下载
}
每种方法适用于不同场景,需根据实际需求选择实现方式。安全验证和内存管理是文件下载功能的关键考虑因素。






