All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Create Zip File After Upload Using PHP

Last Updated : Jul 1, 2023

IN - PHP HTML | Written & Updated By - Anjali

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.

I hope this tutorial on create zip file php helps you and the steps and method mentioned above are easy to follow and implement.