How to zip a whole folder using PHP

前端 未结 15 2464
有刺的猬
有刺的猬 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:14

    This is a function that zips a whole folder and its contents in to a zip file and you can use it simple like this :

    addzip ("path/folder/" , "/path2/folder.zip" );
    

    function :

    // compress all files in the source directory to destination directory 
        function create_zip($files = array(), $dest = '', $overwrite = false) {
        if (file_exists($dest) && !$overwrite) {
            return false;
        }
        if (($files)) {
            $zip = new ZipArchive();
            if ($zip->open($dest, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
                return false;
            }
            foreach ($files as $file) {
                $zip->addFile($file, $file);
            }
            $zip->close();
            return file_exists($dest);
        } else {
            return false;
        }
    }
    
    function addzip($source, $destination) {
        $files_to_zip = glob($source . '/*');
        create_zip($files_to_zip, $destination);
        echo "done";
    }
    

提交回复
热议问题