php实现批量下载
PHP实现批量下载的方法
通过PHP实现批量下载文件通常需要将多个文件打包成ZIP格式或直接逐个下载。以下是两种常见方法的实现步骤。

使用ZIP打包下载
需要确保服务器已安装ZipArchive扩展,该方法适用于将多个文件压缩后一次性下载。

$files = ['file1.jpg', 'file2.pdf', 'file3.txt']; // 文件路径数组
$zipname = 'downloads.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
if (file_exists($file)) {
$zip->addFile($file, basename($file));
}
}
$zip->close();
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . $zipname . '"');
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
unlink($zipname); // 删除临时ZIP文件
逐个文件下载
若需逐个下载而非打包,可通过循环处理文件并设置HTTP头实现。
$files = ['file1.jpg', 'file2.pdf', 'file3.txt'];
foreach ($files as $file) {
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Content-Length: ' . filesize($file));
readfile($file);
exit; // 每次下载一个文件后退出
}
}
注意事项
- 文件路径需为服务器绝对路径或相对路径,确保PHP有读取权限。
- 大文件下载时需考虑内存限制,可使用
chunked分块读取。 - 若文件来自用户输入,需严格验证路径防止目录遍历攻击。
处理远程文件
若需下载远程URL文件,可先用file_get_contents或CURL获取内容再保存到临时目录。
$urls = ['http://example.com/file1.jpg', 'http://example.com/file2.pdf'];
$tempDir = 'temp_downloads/';
foreach ($urls as $url) {
$content = file_get_contents($url);
$filename = $tempDir . basename($url);
file_put_contents($filename, $content);
}
// 之后可调用ZIP打包或逐个下载






