/**
* 循环压缩目录文件
* @param $path 文件夹路径
* @param $zip 压缩后zip名字及路径
*/
function addFileToZip($path, $zip)
{
$handler = opendir($path); //打开当前文件夹由$path指定。
while (($filename = readdir($handler)) !== false) {
//文件夹文件名字为'.'和‘..’,不要对他们进行操作
if ($filename != "." && $filename != "..") {
// 如果读取的某个对象是文件夹,则递归
if (is_dir($path . "/" . $filename)) {
addFileToZip($path . "/" . $filename, $zip);
} else {
//将文件加入zip对象
$zip->addFile($path . "/" . $filename);
$zip->renameName($path . $filename, '11');
}
}
}
@closedir($path);
}
/**
* 多目录压缩
*/
function textDownload1()
{
$zip = new \ZipArchive();
$username = $_SESSION['adminUser'];
$zipname = $username . '.zip';
$zipPath = './Public/doc/history/' . $zipname;
if ($zip->open("$zipPath", \ZipArchive::CREATE) === TRUE) {
$this->addFileToZip("./Public/doc/$username/", $zip); //调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法
$zip->close(); //关闭处理的zip文件
//设置打包完自动下载
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename=' . $zipname);
header('Content-Length: ' . filesize($zipPath));
readfile($zipPath);
unlink("./Public/doc/history/$username.zip");
}
}
/**
* 多文件压缩
*/
function textDownload()
{
$username = $_SESSION['adminUser'];
$zipname = $username . '.zip';
$fileList = array(
"./Public/doc/$username/answer.docx",
"./Public/doc/$username/test.docx"
);
$filepath = './Public/doc/history/' . $zipname;
$zip = new \ZipArchive();
$zip->open($filepath,\ZipArchive::CREATE); //打开压缩包
foreach($fileList as $file){
$zip->addFile($file,basename($file)); //向压缩包中添加文件
}
$zip->close(); //关闭压缩包
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename=' . $zipname);
header('Content-Length: ' . filesize($filepath));
readfile($filepath);
}
/**
* @param $path
* 删除文件及目录
*/
function deleteAll($path)
{
$op = dir($path);
while (false != ($item = $op->read())) {
if ($item == '.' || $item == '..') {
continue;
}
if (is_dir($op->path . '/' . $item)) {
deleteAll($op->path . '/' . $item);
rmdir($op->path . '/' . $item);
} else {
unlink($op->path . '/' . $item);
}
}
}
PHP 压缩文件夹
最新推荐文章于 2024-07-26 14:37:55 发布