/**
* 循環壓縮目錄文件
* @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 壓縮文件夾
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.