php 壓縮資料夾
阿新 • • 發佈:2020-07-28
php 壓縮資料夾
例子來源於php官方文件。
<?php { /** * Add files and sub-directories in a folder to zip file. * @param string $folder * @param ZipArchive $zipFile * @param int $exclusiveLength Number of text to be exclusived from the file path. */ private static function folderToZip($folder, &$zipFile, $exclusiveLength) { $handle = opendir($folder); while (false !== $f = readdir($handle)) { if ($f != '.' && $f != '..') { $filePath = "$folder/$f"; // 去除檔案字首地址 $localPath = substr($filePath, $exclusiveLength); if (is_file($filePath)) { //第一個引數是新增檔案的絕對路徑,第二是引數是新增到壓縮包的檔名稱。 $zipFile->addFile($filePath, $localPath); } elseif (is_dir($filePath)) { // 如果是資料夾遞迴新增。 $zipFile->addEmptyDir($localPath); self::folderToZip($filePath, $zipFile, $exclusiveLength); } } } closedir($handle); } /** * Zip a folder (include itself). * Usage: * HZip::zipDir('/path/to/sourceDir', '/path/to/out.zip'); * * @param string $sourcePath Path of directory to be zip. * @param string $outZipPath Path of output zip file. */ public static function zipDir($sourcePath, $outZipPath) { $pathInfo = pathInfo($sourcePath); $parentPath = $pathInfo['dirname']; $dirName = $pathInfo['basename']; $z = new ZipArchive(); $z->open($outZipPath, ZIPARCHIVE::CREATE); $z->addEmptyDir($dirName); self::folderToZip($sourcePath, $z, strlen("$parentPath/")); $z->close(); } }