How to Create a ZIP File using PHP ?

H

Zipped File
Creating a ZIP File using PHP is very simple using the built-in Class “ZipArchive“. All one has to do is create an instance of this class and use the methods of this class to create the zip file. Lets take a look how we can create a zip file.

 

 

The snippet for creating a zip file is

<?php
if (isset($_FILES['upload']) === true ){
$files = $_FILES['upload'];

$zip = new ZipArchive();
$zip->open('zipname.zip', ZipArchive::CREATE);

for( $i = 0; $i < count($files['name']); $i++)
{
$tmpname = $files['tmp_name'][$i];
$name	= $files['name'][$i];

move_uploaded_file($tmpname, $name);
$zip->addFile($name);
}
$zip->close();
echo "File(s) have been zipped";
}
?>

<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="upload[]" multiple>
<input type="submit" value="Archive">
</form>

To understand how we have created the ZIP file, there are 4 very simple steps that involved in creating the zip file.

1. Creating the instance for “ZipArchive” Class.

You have to create an instance for this class using standard PHP syntax. The following PHP Code lets you create an instance for “ZipArchive” class.

$zip = new ZipArchive();

2. Creating/Opening the ZIP File.

Now we are going to create a new ZIP File using its method open which actually opens the zip file but adding one more constant parameter tells the method to create the ZIP File. Following is the syntax to do it and “zipname.zip’ is the name of the new Archive File that should be created.

$zip->open('zipname.zip', ZipArchive::CREATE);

3. Adding Files to the Created ZIP File.

We have created a new archive file using the above method, now we need to add files to the created file. Following is the syntax to add a file to the archive where $name indicates the name of the file in present directory which has to be archived.

$zip->addFile($name);

4. Closing the opened ZIP File.

We are done adding a file to the ZIP file, So lets close the opened file. Following is the syntax to do it.

$zip->close();

Video Tutorial :

About the author

pavankumar.p1990

5 comments

By pavankumar.p1990