php代码实现文件下载
PHP 文件下载实现方法
使用 PHP 实现文件下载功能可以通过设置 HTTP 头部信息并输出文件内容来完成。以下是几种常见方法:
使用 readfile() 函数
$file = 'path/to/file.ext';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
使用 fread() 逐块读取大文件
对于大文件下载,可以分块读取以避免内存问题:
$file = 'large_file.zip';
$chunk_size = 1024*1024; // 1MB chunks
if (file_exists($file)) {
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;
}
强制下载特定类型文件
控制特定文件类型的下载行为:
$file = 'document.pdf';
if (file_exists($file)) {
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="downloaded.pdf"');
readfile($file);
exit;
}
安全下载注意事项
- 验证文件路径,防止目录遍历攻击
- 限制可下载文件目录
- 对用户权限进行检查
安全下载示例:
$base_dir = '/safe/download/directory/';
$requested_file = basename($_GET['file']); // 防止路径遍历
$file_path = $base_dir . $requested_file;
if (file_exists($file_path) && is_file($file_path)) {
// 执行下载逻辑
}
处理中文文件名
解决中文文件名乱码问题:

$file = '中文文件.txt';
$encoded_filename = urlencode($file);
header('Content-Disposition: attachment; filename="'.$encoded_filename.'"');
这些方法覆盖了从简单文件下载到大文件处理、安全考虑以及特殊字符处理等常见需求。根据实际应用场景选择合适的方法,特别注意安全性方面的处理。






