php实现文件的下载
PHP 实现文件下载的方法
在 PHP 中实现文件下载功能通常需要设置正确的 HTTP 头信息,并输出文件内容。以下是几种常见的实现方式:
使用 header() 函数强制下载
通过设置 Content-Disposition 头信息,可以强制浏览器弹出下载对话框而不是直接显示文件内容:

$file = 'path/to/your/file.pdf';
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;
}
指定特定的 MIME 类型
如果需要指定具体的文件类型,可以修改 Content-Type 头:
$file = 'path/to/image.jpg';
if (file_exists($file)) {
header('Content-Type: image/jpeg');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
处理大文件下载
对于大文件,可以使用分块读取的方式避免内存问题:

$file = 'path/to/large/file.zip';
if (file_exists($file)) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
$chunkSize = 1024 * 1024; // 1MB chunks
$handle = fopen($file, 'rb');
while (!feof($handle)) {
echo fread($handle, $chunkSize);
ob_flush();
flush();
}
fclose($handle);
exit;
}
安全注意事项
确保文件路径来自可信来源或经过严格验证,避免目录遍历攻击:
$basePath = '/safe/directory/';
$requestedFile = basename($_GET['file']); // 使用 basename 防止路径遍历
$file = $basePath . $requestedFile;
if (file_exists($file) && is_file($file)) {
// 设置头信息并输出文件
}
处理中文文件名
对于包含非ASCII字符的文件名,需要进行编码处理:
$filename = '中文文件.txt';
header('Content-Disposition: attachment; filename*=UTF-8\'\'' . rawurlencode($filename));
通过以上方法,可以实现安全可靠的PHP文件下载功能。根据实际需求选择适合的方式,并注意安全性问题。






