php实现下载文件
PHP实现下载文件的方法
使用header()函数强制下载
设置合适的HTTP头部信息,强制浏览器下载文件而非直接打开。以下是一个基本示例:
$file_path = '/path/to/your/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));
flush();
readfile($file_path);
exit;
} else {
http_response_code(404);
die('File not found');
}
分块下载大文件
对于大文件,使用分块读取可以降低内存消耗:

$chunk_size = 1024 * 1024; // 1MB per chunk
$handle = fopen($file_path, 'rb');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
flush();
}
fclose($handle);
动态生成内容下载
直接输出动态生成的内容作为下载文件:

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="data.csv"');
$output = fopen('php://output', 'w');
fputcsv($output, ['Name', 'Email', 'Phone']);
fputcsv($output, ['John Doe', 'john@example.com', '123456789']);
fclose($output);
安全注意事项
验证文件路径防止目录遍历攻击:
$base_dir = '/safe/directory/';
$requested_file = $_GET['file'];
$real_path = realpath($base_dir . $requested_file);
if (strpos($real_path, $base_dir) === 0 && file_exists($real_path)) {
// 安全的文件路径
} else {
die('Invalid file path');
}
处理中文文件名
确保中文文件名正确显示:
$encoded_name = rawurlencode($file_name);
header('Content-Disposition: attachment; filename*=UTF-8\'\'' . $encoded_name);
以上方法涵盖了PHP实现文件下载的主要场景,包括静态文件下载、大文件处理和动态内容生成下载。根据实际需求选择合适的方法,并始终注意安全性问题。






