php 实现下载功能
使用 header 函数实现文件下载
在 PHP 中,可以通过设置 HTTP 头部信息实现文件下载功能。以下是一个基本示例:
$file_path = '/path/to/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="' . $file_name . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path));
readfile($file_path);
exit;
} else {
echo '文件不存在';
}
通过文件流动态生成下载内容
如果需要动态生成文件内容(如 CSV 或文本文件),可以直接输出到浏览器:
$content = "姓名,年龄,职业\n张三,25,工程师\n李四,30,设计师";
$file_name = 'data.csv';
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $file_name . '"');
echo $content;
exit;
处理大文件下载
对于大文件下载,可以使用分块读取以避免内存问题:
$file_path = '/path/to/large_file.zip';
$file_name = 'large_file.zip';
if (file_exists($file_path)) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $file_name . '"');
header('Content-Length: ' . filesize($file_path));
$chunk_size = 1024 * 1024; // 1MB 分块
$handle = fopen($file_path, 'rb');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
ob_flush();
flush();
}
fclose($handle);
exit;
}
安全性注意事项
- 验证文件路径,防止目录遍历攻击(如
../)。 - 限制用户权限,确保只能下载允许的文件。
- 使用
basename()清理文件名,避免注入恶意字符。
示例安全处理:
$user_file = $_GET['file'];
$safe_file = basename($user_file);
$file_path = '/safe_dir/' . $safe_file;
以上方法覆盖了从简单文件下载到动态内容生成和大文件处理的常见需求。







