Create Multiple Images Zip Archive Using PHP

php create zip files and add multiple images into zip file using php

If you are looking for a way to create a zip archive using PHP then you are in the right place. PHP already has the ZIP class which can help you to create and extract zip archive. It's very easy to use and understand all you need is the perfect guide to the PHP Zip archive.

So in this PHP tutorial you will learn how to upload multiple images and create a zip archive using PHP. you can use this script for your projects or create a zipper for the archive. We will also show you how you can open Zip archive and display files using PHP.


Download the full script or check the working demo.



Creating files Zip archive


We will use the ZipArchive class to create Zip files. So the first thing we are going to do is to instantiate the ZipArhivce class and then we use if else statement to open Zip file. Then we able to add files using the Addfile function and save the zip file using close function


<?php
//instantiate the class
$zip = new ZipArchive;
//Set Zip file name
$zip_name = "myzipfile.zip";
//files to create zip
$files ='myfile.jpg';
//Now open to create the zip file 
if ($zip->open($zip_name, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) === TRUE){
    //now add the file into the zip archive
    $zip->addFile($files, 'NewName.jpg');
    //now save the archive using the close function
    $zip->close();
} else {
    echo 'failed';
}
?>

Extracting Zip files


To extract zip files we will simply add the zip file destination first and again we will open zip same as we did above, but this time we will pass zip file destination variable and add extractTo function with the path the folder where we want to extract files.


<?php
//instantiate the class
$zip = new ZipArchive;
//add the Zip file 
$zip_file = "myzipfile.zip";
//Now open to create the zip file 
if ($zip->open($zip_file) === TRUE){
    //now add the file into the zip archive
    $zip->extractTo('/myfolder');
    //now save the archive using the close function
    $zip->close();
} else {
    echo 'failed';
}
?>

Display Zip Files


To list the Zip files you need to add for loop to display Zip files, so first we open the Zip file using the open function. Then we start for loops to get files from the Zip archive then we get the details of an entry defined by its index using the Statindex function.


The main php part which goes to above tag


<?php
//instantiate the class
$zip = new ZipArchive;
//Zip file to open 
$zip_file = "myzipfile.zip";
//Now open to create the zip file 
if ($zip->open($zip_file) === TRUE){
    //get the Zip file names and display
    for( $i = 0; $i < $zip->numFiles; $i++ ){ 
      $stat = $zip->statIndex( $i ); 
      print_r( basename( $stat['name'] ) . PHP_EOL ); 
   }
} else {
    echo 'failed';
}
?>

Upload Multiple images and create Zip archive

As you can see the demo of this script we have created the Zipper to create a Zip archive so when you upload images or files it will create Zip archive and allow you to download.

We commented every lines which helps you to understand how this script works. So you can easily learn how to create files zipper using PHP.


<?php
if(isset($_POST['upload'])){
 //check if files are empty
 if(!empty($_FILES['files']['name'][0])){
  $files = $_FILES['files'];
  //Create new opject
  $zip = new ZipArchive;
  //create file loop for multiple files
   foreach($files['name'] as $key => $filename){
 $fileTmp   = $files['tmp_name'][$key];
 $fileSize  = $files['size'][$key];
 $errors    = $files['error'][$key];
 //get file extensions----------//
 $ext = explode('.', $filename);//
 $ext = strtolower(end($ext));///
 //create zip file name
 $zip_name = time().".zip";
 //create allowed file extensions arrray 
 $allowed_extensions  = array('txt','jpg','png','gif','svg');
 //check if the file is allowed or not
 if(in_array($ext, $allowed_extensions)){
  //Check for errors
 if($errors ===0){
  //check the file sizes (2mb allowed)
  if($fileSize <= 2097152){
   //Generate a unique ID
   $newFilesNames = uniqid('', true) . '.' . $ext;
   //set file root
   $root = 'uploads/' . $newFilesNames;
   //move files to root
    move_uploaded_file($fileTmp, $root);
                         //open Zip file to create archive
    if($zip->open($zip_name, ZIPARCHIVE::CREATE) === TRUE){
                                 //add files into the zip archive
     $zip->addFile($root,$newFilesNames); 
     } 
   //save the archive  
   $zip->close();
  }else{
   $error = '<div class="alert alert-danger" role="alert">[$filename] is too large.</div>';
  }
 }
  }else{
    $error =  '<div class="alert alert-danger" role="alert">The file "'.$filename.'" with the '.$ext.' extension is not allowed</div>';
  }
}//loop end here
        //check if Zip archive is created
 if(file_exists($zip_name)){
   // push to download the zip
   header('Content-type: application/zip');
   header('Content-Disposition: attachment; filename="'.$zip_name.'"');
   readfile($zip_name);
   // remove zip file is exists in temp path
   unlink($zip_name);
  }
  //Dalete uploaded the files
 unlink($root); 
   }
}
?>

The template to upload files


<!DOCTYPE html>
<html lang="en">
 <head>
  <meta name="description" content="Creating files zip arcive using php files like images txt doc and other formats.">
  <meta name="author" content="Aizaz.dinho">
  <meta name="author" content="meralesson.com">
  <title>Create Images Zip Archive Using PHP</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" >
  <link rel="stylesheet" href="css/style.css"/> 
   </head>
<body>
<div class="container">
      <div class="header clearfix">
        <nav>
          <ul class="nav nav-pills pull-right">
            <li role="presentation" class="active"><a href="#">Tutorial</a></li>
            <li role="presentation"><a href="#">Download Codes</a></li>
           </ul>
        </nav>
        <h3 class="text-muted">PHP Zipper</h3>
      </div>
      <div class="jumbotron">
        <h2>Create Zip Archive Using PHP</h2>
        <p class="lead">Create Zip Archive using PHP, just upload your files and make zip archive this is an free PHP script made by <a href="https://www.twitter.com/aizazdinho" rel="author">Aizaz.dinho</a> to upload multiple image and create zip file.</p>
        <!--+++++FORM HERE++++++-->
        <form  method="post" enctype="multipart/form-data">
        <input id="uploadFile" placeholder="Choose File" disabled="disabled" />
    <div class="fileUpload btn btn-primary">#1: Select Files
     <input  id="uploadBtn" name="files[]" type="file" class="upload" multiple  /> </div>
    <label class="btn btn-lg btn-success">#2: Create Zip<input type="submit" name="upload" style="display: none;" value="Zip archive" /></label>
  </form>
  <!--+++++Display ERROR ++++++-->
  <?php if(isset($error)){echo $error;}?>
   </div>
   <!--+++++Script to just add file selection value++++++-->
  <script type="text/javascript">
      document.getElementById("uploadBtn").onchange = function () {
       document.getElementById("uploadFile").value = this.value;
   };
    </script>

      <footer class="footer">
        <p>Script created by <a href="http://www.meralesson.com/">&copy; Meralesson</a>. Template powered by <a href="http://getbootstrap.com/examples/jumbotron-narrow/">Bootstrap</a></p>
      </footer>

    </div> <!-- /container -->
</body>
</html>

We hope you may like this script and learned form it if you do like this tutorial and want more free PHP scripts then make sure to like and follow us on Twitter, Facebook to get latest updates from us.


Follow your heart, All else will follow you - Aizaz.dinho


  • Recommended: How to Get the Visitors IP Address And Locations using PHP
  • Recommended: Check If Website Is Down Using PHP And Curl

  • Comments

    1. I like your examples they are really detailed and well explained

      ReplyDelete

    Post a comment