php 实现下载
PHP 实现文件下载的方法
使用 PHP 实现文件下载可以通过设置 HTTP 头信息,强制浏览器将文件作为附件下载而非直接打开。
基本下载实现
$file_path = 'path/to/your/file.pdf';
$file_name = 'custom_name.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 '文件不存在';
}
大文件分块下载
对于大文件,可以使用分块下载方式减少内存消耗:

$file_path = 'large_file.zip';
$chunk_size = 1024 * 1024; // 1MB chunks
$handle = fopen($file_path, 'rb');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
ob_flush();
flush();
}
fclose($handle);
强制下载特定 MIME 类型
可以指定特定的 MIME 类型强制浏览器下载:

$mime_types = [
'pdf' => 'application/pdf',
'txt' => 'text/plain',
'jpg' => 'image/jpeg'
];
$ext = pathinfo($file_path, PATHINFO_EXTENSION);
if (isset($mime_types[$ext])) {
header('Content-Type: ' . $mime_types[$ext]);
}
安全注意事项
实现下载功能时需注意安全防护:
- 验证文件路径是否在允许的目录范围内
- 禁止用户通过路径遍历下载系统文件
- 对下载文件名进行过滤,防止注入攻击
$base_dir = '/var/www/downloads/';
$requested_file = $_GET['file'];
$real_path = realpath($base_dir . $requested_file);
if (strpos($real_path, $base_dir) === 0 && file_exists($real_path)) {
// 安全下载逻辑
} else {
die('非法文件请求');
}
进度显示实现
如需显示下载进度,可通过 JavaScript 配合 PHP 实现:
// 前端代码示例
fetch('/download.php')
.then(response => {
const reader = response.body.getReader();
const contentLength = +response.headers.get('Content-Length');
let received = 0;
return new ReadableStream({
start(controller) {
function push() {
reader.read().then(({done, value}) => {
if (done) {
controller.close();
return;
}
received += value.length;
updateProgress(received / contentLength);
controller.enqueue(value);
push();
});
}
push();
}
});
});






