Compress images/folders to a zip file in PHP

Home » Programming » Compress images/folders to a zip file in PHP

Compress images/folders to a zip file in PHP

PHP has a useful feature that allows you to compress and download images into a single zip file. Additionally, it offers the choice to download numerous folders that have been compressed into a single zip file. The multiple folder zip option is achievable using the recursive approach. We will be using ZipArchieve library that is provided by PHP.

 

Compress images to a zip file.

Take a look at the example code below, which makes a zip file out of an array of images.

 

Step 1: Function create_zip that has two parameters:

  • Files array of images.
  • Destination folder with default value as empty.
function create_zip($files = array(),$destination = '') {
    $zip = new ZipArchive();
    $zip->open($destination, ZipArchive::CREATE);
    foreach($files as $file){
      $download_file = file_get_contents($file);
      $zip->addFromString(basename($file),$download_file);
    }
    $zip->close();
    header('Content-type: application/zip');
    header('Content-Disposition: attachment; filename='.basename($destination)); 
}

 

Step 2: Array of remote urls for images. All of these will be compressed to a zip file.

$files_to_zip = array(
   'http://www.public-domain-image.com/nature-landscape/garden-park/slides/path-in-peat-moors-in-sumava-national-park.jpg',
   'http://s3.freefoto.com/images/12/54/12_54_2_web.jpg',
   'http://www.public-domain-image.com/free-images/flora-plants/bushes-and-shrubs/bunchberry-bush-725x472.jpg'
);

 

Step 3: Call the step 1 function by passing two arguments:

  • Files array of images to compress.
  • Destination folder as to where it should be stored/downloaded.
create_zip($files_to_zip, /path/to/destination/folder);

Now, all the images from files array are compressed in the destination folder mention in second argument.

 

Compress multiple folders along with its contents to a zip file.

Multiple directories can be compressed into a single file using the same procedure. Along with the text files, photos, and PDFs that are contained inside the folders, it will compress several folders using the recursive approach. The code above needs a few adjustments. Look at the code examples below.

Step 1:  Function Zip that has two parameters:

  • Source folder that users wants to compress.
  • Destination filename.
function Zip($source, $destination){
   if (!extension_loaded('zip') || !file_exists($source)) {
     return false;
   }
   $zip = new ZipArchive();
   if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
     return false;
   }
   $source = str_replace('\\', '/', realpath($source));
   if (is_dir($source) === true){
     $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
     foreach ($files as $file){
       $file = str_replace('\\', '/', $file);
       if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
         continue;
       $file = realpath($file);
       if (is_dir($file) === true){
         $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
       }else if (is_file($file) === true){
         $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
       }
     }
   } else if (is_file($source) === true){
     $zip->addFromString(basename($source), file_get_contents($source));
   }
   return $zip->close();
   header('Content-type: application/zip');
   header('Content-Disposition: attachment; filename='.basename($destination));
}

 

Step 2: If compressed_data.zip the destination filename already exists at the destination then delete it.

if(file_exists($media_dir.'/compressed_data.zip')){
     unlink($media_dir.'/compressed_data.zip');
}

 

All the necessary functions are ready. Now we have to call them with appropriate parameters.

To implement in core PHP we will use it as below:

To compress the folder(selected by user) we will call the function from step 2 by passing two arguments:

  • The folder that needs to be compressed.
  • Filename as to where it should be stored/downloaded. We will name it as compressed_data.zip
Zip(/path/of/the/folder/to/zip, .'/compressed_data.zip');

Now, the entire folder and its contents are contained in the compressed_data.zip file.

 

The same code can be implemented in a WordPress website.

In WordPress the images are stored in the uploads directory. To get the uploads directory we use the the below function.

$upload_dir = wp_upload_dir(); 
$media_dir = $upload_dir['basedir'];

 

In Uploads folder we have created a folder named testZip inside the media directory.

$testzip_dir =  $media_dir.'testZip/';

 

To compress the testZip folder we will call the function from step 2 by passing 2 arguments:

  • The folder that needs to be compressed.
  • Filename as to where it should be stored/downloaded. We will name it as compressed_data.zip
Zip($testzip_dir, $media_dir.'/compressed_data.zip'); 

Now, the entire folder and its contents are contained in the compressed_data.zip file.