Showing posts with label Zip. Show all posts
Showing posts with label Zip. Show all posts

Friday, July 23, 2010

Create Zip Archive File using PHP ZipArchive

Do you want to place certain files on a zip archive file? In php this is possible using the ZipArchive class - a file archive, compressed with Zip. Below is the sample code program of this functionality.


<?php

//sample files in an array to be compressed
$files = array(
    'images/img1.png',
    'images/img2.png',
    'images/img3.png',
    'images/img4.png',
    'images/img5.png'
);

//returns true if creation succeed and false if zip creation failed
$result = create_zip($files,'my-archive.zip');

//function that creates a compressed zip file
function create_zip($files = array(),$destination = '',$overwrite = false) {
    //if the zip file already exists and overwrite is false, return false
    if(file_exists($destination) && !$overwrite) { return false; }
    //variable declaration
    $valid_files = array();
    //if files are valid
    if(is_array($files)) {
        //loops and check each file
        foreach($files as $file) {
            //check if file exists and store in array
            if(file_exists($file)) {
                $valid_files[] = $file;
            }
        }
    }
    //check if there are valid files
    if(count($valid_files)) {
       //create the zip archive object
       $zip = new ZipArchive();
       if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE :     ZIPARCHIVE::CREATE) !== true) {
           return false;
       }
        //add files to the object
        foreach($valid_files as $file) {
          $zip->addFile($file,$file);
        }

       //close the zip after adding the files
        $zip->close();

        //check if the destination file exists
        return file_exists($destination);
    }
    else {
        return false;
    }
}

?>