35 C

PHP: How to compress a folder and download from server using php?

Must read

Ayyaz Zafarhttps://www.ayyaztech.com
I am Full Stack Web Developer with 10 years of professional Experience. I have following Skills: HTML5, CSS3, Javascript, jQuery, Ajax, PHP, MySQL, jQuery, Angular, React.js, Wordpress, Codeigniter, Laravel, Node.js, Mongo DB, Express.js, GraphQL, Typescript, Apollo and many more..

Following script was very helpful to me for compressing A folder (including all sub folders and files in it) using PHP:

$the_folder = 'path/foldername';
$zip_file_name = 'archived_name.zip';

$download_file= true;
//$delete_file_after_download= true; doesnt work!!

class FlxZipArchive extends ZipArchive {
    /** Add a Dir with Files and Subdirs to the archive;;;;; @param string $location Real Location;;;;  @param string $name Name in Archive;;; @author Nicolas Heimann;;;; @access private  **/

    public function addDir($location, $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));
else  { echo 'Could not create a zip archive';}

if ($download_file)
    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));



- Advertisement -spot_img

More articles


Please enter your comment!
Please enter your name here

Latest article