How to zip a whole folder using PHP

前端 未结 15 2255
有刺的猬
有刺的猬 2020-11-22 08:48

I have found here at stackoveflow some codes on how to ZIP a specific file, but how about a specific folder?

Folder/
  index.html
  picture.jpg
  important.tx         


        
15条回答
  •  清酒与你
    2020-11-22 09:24

    Create a zip folder in PHP.

    Zip create method

       public function zip_creation($source, $destination){
        $dir = opendir($source);
        $result = ($dir === false ? false : true);
    
        if ($result !== false) {
    
            
            $rootPath = realpath($source);
             
            // Initialize archive object
            $zip = new ZipArchive();
            $zipfilename = $destination.".zip";
            $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)
            {
                // Skip directories (they would be added automatically)
                if (!$file->isDir())
                {
                    // Get real and relative path for current file
                    $filePath = $file->getRealPath();
                    $relativePath = substr($filePath, strlen($rootPath) + 1);
             
                    // Add current file to archive
                    $zip->addFile($filePath, $relativePath);
                }
            }
             
            // Zip archive will be created only after closing object
            $zip->close();
            
            return TRUE;
        } else {
            return FALSE;
        }
    
    
    }
    

    Call the zip method

    $source = $source_directory;
    $destination = $destination_directory;
    $zipcreation = $this->zip_creation($source, $destination);
    

提交回复
热议问题