0

Following code is working fine, but only zipping one sub folder. My folder structure is like this.

MasterFolder
--example-folder
----TestFolder1
----TestFolder2
----TestFolder3
--example-file1.txt
--example-file2.txt

I need to zip the example-folder along with all the subfolders and files inside the example-folder and sub folders (TestFolder1, TestFolder2, TestFolder3, example-file1.txt, example-file2.txt) as well.

Here is my code.

create-zip-file.php

<?php

$zipArchive = new ZipArchive();
$zipFile = "./example-zip-file.zip";
if ($zipArchive->open($zipFile, ZipArchive::CREATE) !== TRUE) {
    exit("Unable to open file.");
}
$folder = 'example-folder/';
createZip($zipArchive, $folder);
$zipArchive->close();
echo 'Zip file created.';

function createZip($zipArchive, $folder)
{
    if (is_dir($folder)) {
        if ($f = opendir($folder)) {
            while (($file = readdir($f)) !== false) {
                if (is_file($folder . $file)) {
                    if ($file != '' && $file != '.' && $file != '..') {
                        $zipArchive->addFile($folder . $file);
                    }
                } else {
                    if (is_dir($folder . $file)) {
                        if ($file != '' && $file != '.' && $file != '..') {
                            $zipArchive->addEmptyDir($folder . $file);
                            $folder = $folder . $file . '/';
                            createZip($zipArchive, $folder);
                        }
                    }
                }
            }
            closedir($f);
        } else {
            exit("Unable to open directory " . $folder);
        }
    } else {
        exit($folder . " is not a directory.");
    }
}

$filename = "example-zip-file.zip";
if (file_exists($filename)) {
    $absoluteFilePath = __DIR__ . '/' . $filename;
    header('Pragma: public');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Cache-Control: private', false);
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="' . basename($filename) . '";');
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: ' . filesize($absoluteFilePath));
    readfile($absoluteFilePath);
    exit();
}
?>

index.php

<div class='container'>
    <h2>Click Here to Download</h2>
    <p>
        <a href="create-zip-file.php" class="btn btn-primary">Download</a>
    </p>
</div>
SammaDev
  • 11
  • 4

0 Answers0