How to create a zip file in php - Techno Brigade

The latest technology news and information

Breaking

Post Top Ad

Monday 25 September 2017

How to create a zip file in php





To make sure your upload is as smooth and secure as possible, we have to create a zip file when you upload multiple files. Zipping is the process of compressing a bunch of files into a smaller zip file. This will give you the fastest upload possible, and the recipients an equally fast way of downloading the transfer. 
so there is a easy method to zip a file in php

How to zip a file in php

<?php
// path to the file of which we want to make zip
$files_to_zip = array(
            'path/to/folder/fileToZip.txt'
        );
// call function to create zip by passing parrameter as files path and  where we have to store zip file
create_zip($files_to_zip, 'path/to/folder/zipFileName.zip');

    public 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;
        }
        //vars
        $valid_files = array();
        //if files were passed in...
        if (is_array($files)) {
            //cycle through each file
            foreach ($files as $file) {
                //make sure the file exists
                if (file_exists($file)) {
                    $valid_files[] = $file;
                }
            }
        }
        //if we have good files...
        if (count($valid_files)) {
            //create the archive
            $zip = new ZipArchive();
            if ($zip->pen($destination, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
                return false;
            }
            //add the files
            foreach ($valid_files as $file) {
                $zip->addFile($file, $file);
            }
            //debug
            //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
            //close the zip -- done!
            $zip->close();

            //check to make sure the file exists
            return file_exists($destination);
        } else {
            return false;
        }
    
?>


No comments:

Post a Comment

Post Bottom Ad