Batch download
<?php
class PackZip
{
/**
* @param $tmpDir 临时目录
* @param $fileList 文件列表
* @param $packName 打包后的文件名
*/
public static function packFile($tmpDir,$fileList,$packName){
$path = rtrim($tmpDir,'/').'/'.$packName.'/';
if(!is_dir($path)){
mkdir($path,0777,true);
}
$localFile = [];
foreach ($fileList as $k=>$v){
$filename = $v['name'].'.'.pathinfo($v['path'],PATHINFO_EXTENSION);
$localOne = self::netFile2LocalFile($v['path'],$path.$filename);
if($localOne){
$localFile[] = $localOne;
}
}
if($localFile){
// 压缩
$zipname = self::getZipName($tmpDir,$packName);
$zip = new \ZipArchive;
$zip->open($zipname,\ZipArchive::CREATE);
foreach ($localFile as $file) {
$localPath = pathinfo($file,PATHINFO_FILENAME).'.'.pathinfo($file,PATHINFO_EXTENSION);
$zip->addFile($file,$localPath);
}
$zip->close();
return $zipname;
}else{
return false;
}
}
public static function getZipName($tmpDir,$packName){
return rtrim($tmpDir,'/').'/'.$packName.'.zip';
}
public static function delTempFile($tmpDir,$packName){
$dir = rtrim($tmpDir,'/').'/'.$packName.'/';
$zipname = $zipname = self::getZipName($tmpDir,$packName);
if(is_file($zipname)){
@unlink($zipname);
}
if(is_dir($dir)){
$result = scandir($dir);
foreach ($result as $k=>$v){
if($v!='.' && $v!='..'){
@unlink($dir.$v);
}
}
@rmdir($dir);
}
}
/**
* 网络文件路径转换为本地文件路径
* @param $fileUrl 网络文件路径
* @param $filePath 本地文件路径
*/
private static function netFile2LocalFile($fileUrl,$filePath){
if((strpos($fileUrl,'http://')!==false) || (strpos($fileUrl,'https://')!==false)){
// 网络文件
$stream_opts = [
"ssl" => [
"verify_peer"=>false,
"verify_peer_name"=>false,
]
];
$response = file_get_contents($fileUrl, false, stream_context_create($stream_opts));
file_put_contents($filePath,$response);
return $filePath;
}else{
// 本地文件
if(is_file($fileUrl)){
file_put_contents($filePath,file_get_contents($fileUrl));
return $filePath;
}
}
return null;
}
}
Delete the file after the download is complete
$zipname='xxxxx/yyyy.zip';
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.pathinfo($zipname,PATHINFO_FILENAME).'.zip');
header('Content-Length: '.filesize($zipname));
readfile($zipname);
unlink($zipname);