php实现文件下载
PHP 实现文件下载的方法
使用 header() 函数强制下载
设置正确的 HTTP 头信息,强制浏览器下载文件而不是直接打开。
$file = 'path/to/file.pdf';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
处理大文件下载
对于大文件,可以使用分块读取的方式,避免内存问题。
$file = 'path/to/large_file.zip';
$chunk_size = 1024 * 1024; // 1MB chunks
if (file_exists($file)) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
$handle = fopen($file, 'rb');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
ob_flush();
flush();
}
fclose($handle);
exit;
}
动态生成文件并下载
可以直接生成内容并作为文件下载,比如生成 CSV 文件。
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="example.csv"');
$output = fopen('php://output', 'w');
fputcsv($output, ['Name', 'Email', 'Phone']);
fputcsv($output, ['John Doe', 'john@example.com', '123456789']);
fclose($output);
exit;
安全注意事项
确保下载文件时进行权限检查,防止任意文件下载漏洞。
$allowed_files = [
'file1.pdf' => 'path/to/file1.pdf',
'file2.zip' => 'path/to/file2.zip'
];
if (isset($_GET['file']) && array_key_exists($_GET['file'], $allowed_files)) {
$file = $allowed_files[$_GET['file']];
// 使用上面的下载代码
} else {
die('Invalid file request');
}
处理中文文件名
对于包含中文的文件名,需要进行编码转换。
$file = 'path/to/中文文件.pdf';
$filename = rawurlencode(basename($file));
header('Content-Disposition: attachment; filename*=UTF-8\'\'' . $filename);
这些方法涵盖了 PHP 实现文件下载的主要场景,包括基本下载、大文件处理、动态文件生成和安全防护等方面。







