php实现下载功能
PHP 实现文件下载功能
PHP 可以通过多种方式实现文件下载功能,以下是几种常见的方法:
使用 header 函数强制下载
通过设置 HTTP 头部信息,可以强制浏览器下载文件而不是直接打开它。
$file = 'path/to/your/file.pdf'; // 文件路径
$filename = 'custom_filename.pdf'; // 下载时显示的文件名
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
} else {
echo "文件不存在";
}
分块下载大文件
对于大文件,可以使用分块下载方式,减少内存消耗。
$file = 'path/to/large_file.zip';
$chunk_size = 1024 * 1024; // 1MB chunks
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));
$handle = fopen($file, 'rb');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
ob_flush();
flush();
}
fclose($handle);
exit;
}
动态生成文件并下载
可以直接生成内容并提供下载,而不需要物理文件。
$content = "这是一些要下载的文本内容";
$filename = "example.txt";
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Length: ' . strlen($content));
echo $content;
exit;
安全注意事项
- 确保文件路径安全,避免目录遍历攻击
- 验证用户权限后再允许下载
- 对大文件下载设置适当的内存和时间限制
常见问题解决
如果下载文件损坏或无法打开,检查是否正确设置了 Content-Type 头部。不同文件类型应使用对应的 MIME 类型,例如:
- PDF: application/pdf
- ZIP: application/zip
- JPEG: image/jpeg
- PNG: image/png
通过以上方法,可以实现灵活的文件下载功能,满足不同场景需求。







