php下载实现
PHP 文件下载实现方法
在 PHP 中实现文件下载可以通过设置 HTTP 头部信息并输出文件内容来完成。以下是几种常见的实现方式:
使用 header() 函数强制下载
通过设置 Content-Disposition 头部,可以强制浏览器弹出下载对话框:

$file = 'path/to/file.pdf';
$filename = 'custom_name.pdf';
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
分块下载大文件
对于大文件,可以使用分块读取方式减少内存占用:
$file = 'large_file.zip';
$chunk_size = 1024 * 1024; // 1MB chunks
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
$handle = fopen($file, 'rb');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
ob_flush();
flush();
}
fclose($handle);
exit;
动态生成内容下载
可以直接将字符串内容作为文件提供下载:

$content = "This will be downloaded as text file";
$filename = "data.txt";
header('Content-Type: text/plain');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Length: ' . strlen($content));
echo $content;
exit;
安全注意事项
实现文件下载时需注意安全防护:
// 验证文件路径是否在允许目录中
$base_dir = '/safe/download/directory/';
$requested_file = $_GET['file'];
$real_path = realpath($base_dir . $requested_file);
if (strpos($real_path, $base_dir) !== 0) {
die('Invalid file path');
}
// 继续处理下载...
常见 MIME 类型设置
根据文件类型设置正确的 Content-Type:
- PDF:
application/pdf - ZIP:
application/zip - JPEG:
image/jpeg - PNG:
image/png - CSV:
text/csv - Excel:
application/vnd.ms-excel
以上方法涵盖了 PHP 实现文件下载的主要场景,可根据实际需求选择适合的方式。






