php实现下载
使用 PHP 实现文件下载
通过 PHP 实现文件下载需要设置正确的 HTTP 头信息,确保浏览器将响应视为文件下载而非直接显示内容。

基本文件下载方法
$file_path = '/path/to/your/file.pdf'; // 文件路径
$file_name = 'download.pdf'; // 下载时显示的文件名
if (file_exists($file_path)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $file_name . '"');
header('Content-Length: ' . filesize($file_path));
readfile($file_path);
exit;
} else {
echo '文件不存在';
}
动态生成内容并下载
如果需要下载动态生成的内容(如 CSV 或文本数据),可以直接输出内容并设置适当的头信息。

$data = "姓名,年龄,性别\n张三,25,男\n李四,30,女"; // CSV 数据示例
$file_name = 'data.csv';
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $file_name . '"');
echo $data;
exit;
大文件分块下载
对于大文件,可以使用分块读取的方式避免内存问题。
$file_path = '/path/to/large/file.zip';
$file_name = 'large_file.zip';
$chunk_size = 1024 * 1024; // 1MB 每块
if (file_exists($file_path)) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $file_name . '"');
header('Content-Length: ' . filesize($file_path));
$handle = fopen($file_path, 'rb');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
ob_flush();
flush();
}
fclose($handle);
exit;
} else {
echo '文件不存在';
}
强制下载而非浏览器预览
某些文件类型(如 PDF 或图片)可能被浏览器直接打开而非下载。通过设置 Content-Disposition 为 attachment 可强制下载。
$file_path = '/path/to/image.jpg';
$file_name = 'image.jpg';
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename="' . $file_name . '"');
readfile($file_path);
exit;
安全注意事项
- 验证文件路径,避免目录遍历攻击(如
../)。 - 限制用户可下载的文件范围,防止未授权访问。
- 对于动态生成的文件,清理输入数据以避免注入风险。
以上方法覆盖了常见的文件下载场景,可根据实际需求调整头信息或逻辑。






