php实现下载文件
使用 header() 函数实现文件下载
通过设置 HTTP 头信息强制浏览器下载文件而非直接打开。适用于服务器本地文件或动态生成的内容。
$file_path = '/path/to/file.pdf'; // 文件路径
$file_name = 'document.pdf'; // 下载时显示的文件名
if (file_exists($file_path)) {
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;
} else {
die('File not found');
}
处理大文件下载
对于大文件,使用分块读取避免内存溢出:
$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);
动态生成文件内容下载
适用于需要即时生成 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, ['John Doe', 'john@example.com']); // 数据行
fclose($output);
安全注意事项
验证文件路径防止目录遍历攻击:
$base_dir = '/safe/directory/';
$requested_file = $_GET['file'];
$real_path = realpath($base_dir . $requested_file);
if ($real_path && strpos($real_path, $base_dir) === 0) {
// 安全处理下载
} else {
die('Invalid file path');
}
处理中文文件名
解决中文文件名乱码问题:

$encoded_name = rawurlencode('中文文件.txt');
header('Content-Disposition: attachment; filename*=UTF-8\'\'' . $encoded_name);
以上方法涵盖了从简单文件下载到大文件处理、动态内容生成以及安全防护等常见场景。根据实际需求选择合适的方式,注意始终验证用户输入和文件路径。






