How to create zip file using PHP

  •  
  •  
  •  
  •  
  •  
  •  

One of the most popular and vastly used compression format is zip. Any number of files and folders can be stored within a zip file in a compressed size. “.zip” is the extension of the zip file. One of the built in classes of PHP is ZipArchive and you need this class for creating zip file. ZipArchive was introduced in PHP version 5.2 therefore your PHP version should be 5.2 or greater. So friends, in this tutorial you will see how to create zip file using PHP.

How to create zip file using php

 

How to create zip file using PHP

Let’s see the following example which shows you how to create zip file using php. I have created a simple php script which will create the zip file with dynamic name.

<?php	
  //First check whether zip extension is enabled or not
  if(extension_loaded('zip')) {
    $zip = new ZipArchive();
    
    //Creating a dynamic name of the zip file
    $dynamic_zip_name = date('d-m-Y_H-i-s').".zip";
    if($zip->open($dynamic_zip_name, ZipArchive::CREATE) === TRUE) {
    
      //Add some files to the zip file
      $zip->addFile('mitrajit.jpg');
      
      //Add a existing image with a new name
      $zip->addFile('create-zip-file.png', 'sample.png');
      
      //Add image in the image folder with new name
      $zip->addFile("featured.jpg", "files/main-featured.jpg");
      
      //Add a new file sample.txt with the following contents specified in example folder
      $zip->addFromString('example/sample.txt', 'text to be added to the sample.txt file');
     
      //Add an empty folder
      $zip->addEmptyDir("empty_folder");
      
      //Close
      $zip->close();
      
      if(file_exists($dynamic_zip_name)) {
        $file_info = finfo_open(FILEINFO_MIME_TYPE);
        $mime_type = finfo_file($file_info, $dynamic_zip_name);
        $name = basename($dynamic_zip_name);
        header('Content-type: '.$mime_type);
        header('Content-Disposition: attachment; filename="' . $name . '"');
        readfile($dynamic_zip_name);
        unlink($dynamic_zip_name); 
      }
    }
  } else {
      echo "zip extension is not enabled!";
  }
?>
<?php
      //First check whether zip extension is enabled or not
      if(extension_loaded('zip')) {
           $zip = new ZipArchive();
?>

Check whether the zip extension is enabled or not. If yes, then create an object of the ZipArchive class. This object will help you to call various default functions of the ZipArchive class. Each and every time a unique dynamic name will create for the zip file. I have used date and time for dynamic name creation.

<?php if($zip->open($dynamic_zip_name, ZipArchive::CREATE) === TRUE) { ?>

The above line indicates that a new zip file will create. If you want to overwrite an existing zip file then you should use write “OVERWRITE” in place of “CREATE” like below.

<?php if($zip->open($dynamic_zip_name, ZipArchive::OVERWRITE) === TRUE) { ?>

 

<?php	
      //Add some files to the zip file
      $zip->addFile('mitrajit.jpg');

      //Add a existing image with a new name
      $zip->addFile('create-zip-file.png', 'sample.png');
?>

You can add files in the zip as it is. Also you can add files in the zip with new names.

<?php	
      //Add image in the image folder with new name
      $zip->addFile("featured.jpg", "files/main-featured.jpg");
?>

You can add files to any folder  or sub folder.

<?php	
      // Add a new file sample.txt with the following contents specified in example folder
      $zip->addFromString('example/sample.txt', 'text to be added to the sample.txt file');

      //Add an empty folder
      $zip->addEmptyDir("empty_folder");
?>

You can add sample text file with predefined text contents  in it. Also it is possible to add empty folders in it.

<?php
     //Close the object
     $zip->close();
?>

When a file is set to be added to the archive, PHP will lock the file. The lock is only released when the ZipArchive object has been closed via close() function.

<?php
  //Checking whether the created zip file is exists or not
  if(file_exists($dynamic_zip_name)) {
    $file_info = finfo_open(FILEINFO_MIME_TYPE);
    $mime_type = finfo_file($file_info, $dynamic_zip_name);
    $name = basename($dynamic_zip_name);
    //Push the created zip file to the browser for download
    header('Content-type: '.$mime_type);
    header('Content-Disposition: attachment; filename="' . $name . '"');
    readfile($dynamic_zip_name);
    //At last remove the file
    unlink($dynamic_zip_name); 
 }
?>

At last you should push the zip file with proper mime type to the browser for download.

Here is the complete code of the article “How to create zip file using php” —

<?php
if(isset($_POST['createZip'])) {
  
  //First check whether zip extension is enabled or not
  if(extension_loaded('zip')) {
    $zip = new ZipArchive();
    
    //Creating a dynamic name of the zip file
    $dynamic_zip_name = date('d-m-Y_H-i-s').".zip";
    if($zip->open($dynamic_zip_name, ZipArchive::CREATE) === TRUE) {
      //echo "Not enabled!";
    
      //Add some files to the zip file
      $zip->addFile('mitrajit.jpg');
      
      //Add a existing image with a new name
      $zip->addFile('create-zip-file.png', 'sample.png');
      
      //Add image in the image folder with new name
      $zip->addFile("featured.jpg", "files/main-featured.jpg");
      
      //Add a new file sample.txt with the following contents specified in example folder
      $zip->addFromString('example/sample.txt', 'text to be added to the sample.txt file');
      
      //Add an empty folder
      $zip->addEmptyDir("empty_folder");
      
      //Close
      $zip->close();
      
      //Checking whether the created zip file is exists or not
      if(file_exists($dynamic_zip_name)) {
        $file_info = finfo_open(FILEINFO_MIME_TYPE);
        $mime_type = finfo_file($file_info, $dynamic_zip_name);
        $name = basename($dynamic_zip_name);
        //Push the created zip file to the browser for download
        header('Content-type: '.$mime_type);
        header('Content-Disposition: attachment; filename="' . $name . '"');
        readfile($dynamic_zip_name);
        //At last remove the file
        unlink($dynamic_zip_name); 
      }
    }
  } else {
    echo "zip extension is not enabled!";
  }
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>How to create zip file using PHP || Mitrajit's Tech Blog</title>
<style>
span { clear:both; display:block; margin-bottom:30px; }
span a { font-weight:bold; color:#0099FF; }
table { margin-top:30px; }
.msg-div { margin-top:20px; }
</style>
</head>

<body>
  <span>Read the full article -- <a href="http://www.mitrajit.com/2016/10/create-zip-file-using-php/" target="_blank">How to create zip file using PHP</a> in Mitrajit's Tech Blog</span>
  
  <form action="" method="post">
    <input type="submit" name="createZip" value="Create Zip" />
  </form>
</body>
</html>

If you enjoy this article and think it is useful then please share this article with others.

About Mitrajit

Leave a Reply

Your email address will not be published. Required fields are marked *

Prove you are a human *