Search code examples
phpziphide

How to ZIP an entire folder in PHP, even the empty ones?


I'm trying to download a zip from a folder that i have on my app (Laravel 5.8), it's working but they skip all empty folders, and I need them in the zip.

I already tried ZipArchive (php) and chumper/zipper from composer.

Any idea of how can i do this?

This is a Linux Server, running MySQL 5, PHP 7.2 and Apache2.

$files = glob($folder_path);
\Zipper::make($folder_path.'/'.$folder_main_name.'.zip')->add($files)->close();

This lib only accepts glob, but if you have any solution that works, i can easily abandon this.


Solution

  • // Initialize archive object
    $zip = new ZipArchive();
    $zip->open($zipFilename, ZipArchive::CREATE | ZipArchive::OVERWRITE);
    
    // Create recursive directory iterator
    /** @var SplFileInfo[] $files */
    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($rootPath), RecursiveIteratorIterator::LEAVES_ONLY);
    
    foreach ($files as $name => $file)
    {
        // Get real and relative path for current file
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);
    
        if (!$file->isDir())
        {
            // Add current file to archive
            $zip->addFile($filePath, $relativePath);
        }else {
            if($relativePath !== false)
                $zip->addEmptyDir($relativePath);
        }
    }
    
    // Zip archive will be created only after closing object
    $zip->close();
    

    Hi. I modified the previous answer and now I get the zip file including the empty folders. I hope this helps.