Create Zip File After Upload Using PHP

Saturday, Jan 21, 2017

Tags:- PHP HTML


In this tutorial we will show you how to create zip file after upload using php and php inbuilt zip library.Zip files are very useful for copy from one directory to another you can add infinite files in one zip file and it is also easy to maintain there are also various softwares to create a zip file but in this we create zip file using php.You may also like download and extract zip file using PHP.


Create Zip File After Upload Using PHP


To Create Zip File It Takes Only Two Steps:-

  1. Make a HTML file to upload file
  2. Make a PHP file to save and create zip file


Step 1.Make a HTML file to upload file

We make a HTML file and save it with a name upload_file.html

<html>
<body>
<form method="post" action="create_zip.php" enctype="multipart/form-data">
 <input type="file" name='file'>
 <input type="submit" name="upload_file">
</form>
</body>
</html>

In this step we create a form to upload file and then send the file to create_zip.php file which we were going to create in next step.



Step 2.Make a PHP file to save and create zip file

We make a PHP file and save it with a name create_zip.php

<?php
if(isset($_POST['upload_file']))
{
 $uploadfile=$_FILES["file"]["tmp_name"];
 $folder="images/";
 $file_name=$_FILES["file"]["name"];
 move_uploaded_file($_FILES["file"]["tmp_name"], "$folder".$_FILES["file"]["name"]);

 $zip = new ZipArchive(); // Load zip library 
 $zip_name ="upload.zip"; // Zip name
 if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE)
 { 
  echo "Sorry ZIP creation failed at this time";
 }
 $zip->addFile("images/".$file_name);
 $zip->close();
}
?>

In this step we simply upload the file and save it to images folder and then load zip library and set a name 'upload.zip' to zip the zip file which we were creating in next line then we create zip file using ZIPARCHIVE::CREATE and then add uploaded file using addFile() function in this it takes two parameters 1st is file location and 2nd is file name and then after insert file to zip file we close the zip file.You may also like create, edit and delete file using PHP.



Thats all, this is how to create zip file after upload using PHP and HTML.You can customize this code further as per your requirement. And please feel free to give comments on this tutorial.

Join Us With Our 21000+ Subscribers And Get Our Latest Tutorials Update Via Email