Home >Backend Development >PHP Tutorial >How to Zip a Complete Folder and Optionally Delete Its Contents Using PHP?

How to Zip a Complete Folder and Optionally Delete Its Contents Using PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-12-27 10:22:11756browse

How to Zip a Complete Folder and Optionally Delete Its Contents Using PHP?

Zipping a Complete Folder with 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn