Skip to content
Advertisement

Adding subfolders to zip file in php (laravel)

I have a function which is working fine to create zip file from folder files. But recently I’ve had need to add sub-folders into my main folder and now I see my function does not add those sub-folders and files in them into generated zip file.

here is what I have currently:

$zip = new ZipArchive;

if ($zip->open(public_path('Downloads/new_zip.zip'), ZipArchive::CREATE) === TRUE)
{
    $files = File::files(public_path('new_zip'), true);
    foreach ($files as $key => $value) {
        $relativeNameInZipFile = basename($value);
        $zip->addFile($value, $relativeNameInZipFile);
    }
    $zip->close();
}

By using code above, let say I have following structure:

new_zip
 sample.txt

It works fine to create zip file for my folder.

But

If my folder structure is like:

new_zip
 sample.txt
 folder_a
  file_a.txt
 folder_b
  folder_c
   file_c.txt

Then it ignores everything from folder_a and beyond.

Any suggestions?

Advertisement

Answer

You can use this method

The 1st argument is the path to the directory whose data you want to compress

The 2nd argument is the path to the resulting zip file

for your case:

createZipArchive(public_path('new_zip'), public_path('Downloads/new_zip.zip'))
function createZipArchive(string $sourceDirPath, string $resultZipFilePath): bool
{
    $zip = new ZipArchive();
    if (true !== $zip->open($resultZipFilePath, ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
        return false;
    }

    /** @var SplFileInfo[] $files */
    $files = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($sourceDirPath),
        RecursiveIteratorIterator::LEAVES_ONLY
    );

    foreach ($files as $file) {
        $filePath = $file->getRealPath();
        if ($file->isDir() || !$filePath) {
            continue;
        }
        $relativePath = substr($filePath, strlen($sourceDirPath) + 1);
        $zip->addFile($filePath, $relativePath);
    }

    return $zip->close();
}

This method will fully reproduce the folder structure of the source directory.

and a little bit of clarification:

  1. To add the directory “test_dir” and the file “test.txt” to the archive – you just need to do:
$zip->addFile($filePath, "test_dir/test.txt");
  1. The RecursiveDirectoryIterator and RecursiveIteratorIterator are used to recursively traverse the directories of the source folder. They are part of the standard php library. You can read about them in the official php documentation
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement