How to zip a folder and download it using php?

前端 未结 5 2136
伪装坚强ぢ
伪装坚强ぢ 2020-12-15 15:01

I have folder named \"data\". This \"data\" folder contains a file \"filecontent.txt\" and another folder named \"Files\". The \"Files\" folder contains a \"info.txt\" file.

5条回答
  •  无人及你
    2020-12-15 15:36

    ========= The only solution for me ! ! !==========

    Puts all subfolders and sub-files with their structure:

    addEmptyDir($name);
    
            $this->addDirDo($location, $name);
         } // EO addDir;
    
        /**  Add Files & Dirs to archive;;;; @param string $location Real Location;  @param string $name Name in Archive;;;;;; @author Nicolas Heimann
         * @access private   **/
        private function addDirDo($location, $name) {
            $name .= '/';
            $location .= '/';
    
            // Read all Files in Dir
            $dir = opendir ($location);
            while ($file = readdir($dir))
            {
                if ($file == '.' || $file == '..') continue;
                // Rekursiv, If dir: FlxZipArchive::addDir(), else ::File();
                $do = (filetype( $location . $file) == 'dir') ? 'addDir' : 'addFile';
                $this->$do($location . $file, $name . $file);
            }
        } // EO addDirDo();
    }
    
    $za = new FlxZipArchive;
    $res = $za->open($zip_file_name, ZipArchive::CREATE);
    if($res === TRUE) 
    {
        $za->addDir($the_folder, basename($the_folder));
        $za->close();
    }
    else  { echo 'Could not create a zip archive';}
    
    if ($download_file)
    {
        ob_get_clean();
        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($zip_file_name) . ";" );
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: " . filesize($zip_file_name));
        readfile($zip_file_name);
    
        //deletes file when its done...
        //if ($delete_file_after_download) 
        //{ unlink($zip_file_name); }
    }
    ?>
    

提交回复
热议问题