php实现文件下载
PHP实现文件下载的方法
通过PHP实现文件下载功能,可以采用多种方式,以下是几种常见的实现方法:
使用header()函数强制下载
设置HTTP头信息,强制浏览器下载文件而非直接打开:
$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('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path));
readfile($file_path);
exit;
分块下载大文件
对于大文件下载,可以采用分块读取方式,避免内存溢出:
$file_path = '/path/to/large_file.zip';
$chunk_size = 1024 * 1024; // 1MB chunks
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file_path).'"');
$handle = fopen($file_path, 'rb');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
ob_flush();
flush();
}
fclose($handle);
exit;
动态生成文件并下载
当需要动态生成文件内容时,可以直接输出到浏览器:
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);
exit;
安全注意事项
- 验证文件路径,防止目录遍历攻击:
$base_dir = '/safe/directory/'; $file_name = $_GET['file']; $file_path = realpath($base_dir . $file_name);
if (strpos($file_path, $base_dir) !== 0 || !file_exists($file_path)) { die('Invalid file'); }
- 设置适当的MIME类型,确保浏览器正确处理文件类型
这些方法涵盖了从简单文件下载到大文件处理的各种场景,开发者可以根据具体需求选择合适的方式实现文件下载功能。






