php实现批量下载
PHP实现批量下载的方法
使用PHP实现批量下载功能通常涉及文件压缩、HTTP头设置和文件遍历。以下是几种常见的实现方式:
方法一:压缩后下载多个文件
创建ZIP压缩包并下载:

$files = ['file1.txt', 'file2.jpg', 'file3.pdf'];
$zipname = 'downloads.zip';
$zip = new ZipArchive();
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
if (file_exists($file)) {
$zip->addFile($file);
}
}
$zip->close();
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.basename($zipname).'"');
header('Content-Length: '.filesize($zipname));
readfile($zipname);
unlink($zipname);
方法二:直接输出多个文件
通过HTTP头设置实现多个文件逐个下载:

$fileList = [
'file1.txt' => 'text/plain',
'file2.jpg' => 'image/jpeg'
];
foreach ($fileList as $filename => $mimeType) {
if (file_exists($filename)) {
header('Content-Type: '.$mimeType);
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Content-Length: '.filesize($filename));
readfile($filename);
flush();
}
}
方法三:使用队列异步下载
对于大量文件,可以使用队列系统处理:
// 存储下载任务到数据库
$downloadTasks = [
['url' => 'http://example.com/file1', 'name' => 'doc1.pdf'],
['url' => 'http://example.com/file2', 'name' => 'doc2.pdf']
];
// 后台处理脚本
foreach ($downloadTasks as $task) {
$content = file_get_contents($task['url']);
file_put_contents('/downloads/'.$task['name'], $content);
}
注意事项
确保服务器有足够的内存处理大文件
设置适当的超时时间:set_time_limit(0)
考虑使用临时目录存储中间文件
对用户提供的文件名进行安全过滤
安全考虑
验证用户权限后再允许下载 限制可下载的目录范围 使用basename()防止目录遍历攻击 对大文件下载考虑断点续传实现






