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
Release: 2024-12-27 10:22:11
Original
782 people have browsed it

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();
Copy after login

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);
}
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template