php实现批量下载
PHP实现批量下载的方法
使用ZipArchive类打包下载
创建临时压缩包,将多个文件打包后提供下载链接。示例代码:
$zip = new ZipArchive();
$zipName = 'downloads.zip';
if ($zip->open($zipName, ZipArchive::CREATE) === TRUE) {
$files = ['file1.pdf', 'file2.jpg', 'file3.docx'];
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 = [
'/path/to/file1.txt',
'/path/to/file2.txt'
];
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="combined_files.bin"');
foreach ($fileList as $file) {
if (file_exists($file)) {
readfile($file);
}
}
异步队列处理大文件批量下载
对于大型批量下载任务,建议采用队列系统:

// 生产者部分(添加下载任务到队列)
$downloadJobs = [
['url' => 'http://example.com/file1', 'saveAs' => 'local1.ext'],
['url' => 'http://example.com/file2', 'saveAs' => 'local2.ext']
];
foreach ($downloadJobs as $job) {
file_put_contents('download_queue.txt', json_encode($job)."\n", FILE_APPEND);
}
// 消费者部分(后台处理)
while (true) {
$queue = file('download_queue.txt');
if (!empty($queue)) {
$job = json_decode(array_shift($queue), true);
file_put_contents($job['saveAs'], file_get_contents($job['url']));
file_put_contents('download_queue.txt', implode('', $queue));
}
sleep(5);
}
注意事项
- 设置合理的执行时间限制:
set_time_limit(0) - 处理内存限制:
ini_set('memory_limit', '1024M') - 对于远程文件下载,考虑使用cURL代替file_get_contents
- 添加权限验证防止未授权访问
- 记录下载日志用于审计追踪
安全增强措施
验证文件路径防止目录遍历攻击:
function safeDownload($filePath) {
$baseDir = '/secure/download/directory/';
$realPath = realpath($baseDir . $filePath);
if (strpos($realPath, $baseDir) === 0 && file_exists($realPath)) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($realPath).'"');
readfile($realPath);
} else {
header('HTTP/1.0 404 Not Found');
}
}






