在PHP中实现文件下载功能通常涉及设置正确的HTTP头信息,然后将文件内容输出到浏览器。以下是一个简单的示例代码,用于从服务器下载文件:
<?php
// 文件路径
$file_path = 'path/to/your/file.zip'; // 替换为你的文件路径
// 检查文件是否存在
if (!file_exists($file_path)) {
die("File not found.");
}
// 获取文件的基本信息
$file_name = basename($file_path);
$file_size = filesize($file_path);
// 设置HTTP头信息
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: ' . $file_size);
// 清空输出缓冲区并关闭输出缓冲
flush();
// 读取文件并输出到浏览器
readfile($file_path);
// 终止脚本执行
exit;
代码说明:
-
文件路径:
- 将
$file_path
设置为要下载文件的完整路径。
- 将
-
检查文件是否存在:
- 使用
file_exists()
函数检查文件是否存在。如果不存在,输出错误信息并终止脚本。
- 使用
-
设置HTTP头信息:
Content-Description: File Transfer
:表明这是一个文件传输。Content-Type: application/octet-stream
:设置内容类型为二进制流,适用于所有文件类型。Content-Disposition: attachment; filename="..."
:指定下载时的默认文件名。Expires: 0
、Cache-Control: must-revalidate
、Pragma: public
:控制缓存行为。Content-Length
:指定文件大小。
-
输出文件内容:
- 使用
readfile()
函数读取文件并直接输出到浏览器。
- 使用
-
终止脚本:
- 使用
exit
确保脚本在文件输出后立即终止。
- 使用
注意事项:
- 确保PHP脚本有权限读取指定文件。
- 对于大文件,
readfile()
可能不是选择,因为它会将整个文件读入内存。可以考虑使用fopen()
和fread()
分块读取文件。 - 根据文件类型,可能需要调整
Content-Type
头信息以提供更具体的MIME类型。 - 在生产环境中,考虑添加更多的错误处理和安全性检查,例如防止目录遍历攻击。