Home >Backend Development >PHP Tutorial >How to Zip a Complete Folder and Optionally Delete Its Contents Using PHP?
Question:
How can you create a ZIP archive of an entire folder using PHP? Additionally, how do you delete all the contents of the folder after zipping it, excluding a specific file?
Answer:
1. Zip Whole Folder:
$rootPath = rtrim($rootPath, '\/'); $rootPath = realpath('folder-to-zip'); $zip = new ZipArchive(); $zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE); $files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($rootPath), RecursiveIteratorIterator::LEAVES_ONLY ); foreach ($files as $file) { if (!$file->isDir()) { $filePath = $file->getRealPath(); $relativePath = substr($filePath, strlen($rootPath) + 1); $zip->addFile($filePath, $relativePath); } } $zip->close();
2. Zip Whole Folder Delete All Files Except "important.txt":
$rootPath = rtrim($rootPath, '\/'); $rootPath = realpath('folder-to-zip'); $zip = new ZipArchive(); $zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE); $filesToDelete = array(); $files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($rootPath), RecursiveIteratorIterator::LEAVES_ONLY ); foreach ($files as $file) { if (!$file->isDir()) { $filePath = $file->getRealPath(); $relativePath = substr($filePath, strlen($rootPath) + 1); $zip->addFile($filePath, $relativePath); if ($file->getFilename() != 'important.txt') { $filesToDelete[] = $filePath; } } } $zip->close(); foreach ($filesToDelete as $file) { unlink($file); }
The above is the detailed content of How to Zip a Complete Folder and Optionally Delete Its Contents Using PHP?. For more information, please follow other related articles on the PHP Chinese website!