Compress and create a zip file in PHP

In this article, we will discuss how to create a zip file and how to compress data items in it.

Firstly, we have to understand what exactly a zip file is.

What is a zip file?

zip file is the most popular archive format used to group one or more file/folder into a single and secure file.

Files are compressed within a single zip file, thus it can save a lot of space. Many extensions are used for zip files such as- .zip , .rar , .7z etc. The most common used zip format is .zip. So we will discuss how to create a zip file with the .zip  extension in the next section.

Creating a zip file with ZipArchive class in PHP

In PHP, the zip file can be created and modified by creating the object of the ZipArchive class. The required files are locked until the object is destroyed or close()  function is called.

Let us illustrate an example,

<?php
//object of ZipArchive class is created 
$myzip = new ZipArchive;

//New zip file is created and ready to add files in it
if ($myzip->open('new_zipfile.zip', ZipArchive::CREATE) === TRUE)
{
    // Add files to the zip file
    $myzip->addFile('boy.png');
    $myzip->addFile('gray.jpeg');
 
    // Add old.txt file to zip and rename it to newfile.txt
    $myzip->addFile('old.txt', 'new.txt');
 
    // Add a file write.txt file to zip using the text specified
    $myzip->addFromString('write.txt', 'text will be added to the write.txt file');
 
    // closing the zip file.
    $myzip->close();
}
?>

Output:-

create a zip file in PHP



How to make an online zip archiver tool in PHP

This is a real-time example of an online zip archiver tool made for nonprofit purposes. You can also skip this part, as it contains both uploading script as well as zipping script. The source code is given below-

/*
 * This content is copyright by ujwal kumar sahoo
 * licensed by www.codespeedy.com
     */
<html>
<head>
<style>
body {
	padding: 5px 500px;
	font-size: 13px;
    background-color: deepskyblue;
	font-family:serif;
}
h2 {
	margin-bottom: 20px;
	font-family: fantasy;
    font-size: 40px;
}
h3{
	color:green;
}
.container,.container2{
	padding: 10px;
	border: 3px solid black;
	width: 250px;
	color: black;
	box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
}
input{
	padding: 15px;
}
input[type=submit]{
	width: 100px; 
	height: 50px;
	background-color: #474E69; 
	color: #FFF;
	border-radius: 5px;
}
input[type=checkbox] {
font-size:20px;	
}
input[type=file]{
    display: block;
    width: auto;
    font-size: 11px;
    margin-top: 30px;
    border: 3px solid black;
    display: block;
    margin-bottom: 5px;
}
</style>
</head>
<body>
<h2>Upload Files To Create Zip</h2>
<div class="container">
<form method="POST" action="" enctype="multipart/form-data">
<input type="file" name="userfile[]" multiple />
<input type="submit" name="sub" value="UPLOAD" >
</form>
</div>
</body>
</html>
<?php
function reArrayFiles($file_post)
{
	$file_ary=array();
	$file_count=count($file_post['name']);
	$file_keys=array_keys($file_post);
	for($i=0;$i<$file_count;$i++)
	{
		foreach($file_keys as $keys)
		{
			$file_ary[$i][$keys]=$file_post[$keys][$i];
		}
	}
	return $file_ary;
}
if(isset($_POST['sub']))
{
$file_array=reArrayFiles($_FILES['userfile']);
echo"<h2>Select file to zip</h2>
	<div class='container2'>";
echo'<form action="" method="POST">';
for($i=0;$i<count($file_array);$i++)
{
$extensions=array('jpg','img','png','jpeg','docx','xsl','txt','pdf','exe','doc','csv');
$file_ext=explode('.',$file_array[$i]['name']);
$file_ext=end($file_ext);
if(in_array($file_ext,$extensions))
{
	move_uploaded_file($file_array[$i]['tmp_name'],"".$file_array[$i]['name']);
	echo'<input type="checkbox" name="zip_list[]" value="'.$file_array[$i]['name'].'"><label>'.$file_array[$i]['name'].'</label><br>';
}
else
	echo "can't upload the file";
}
echo'<input type="submit" name="zip" value="CREATE" >
</form></div>';
} 
?>
<?php
if(isset($_POST['zip']))
{
	$zip = new ZipArchive;
	if ($zip->open('newzip.zip', ZipArchive::CREATE) === TRUE)
	{
		if(!empty($_POST['zip_list']))
		{
			foreach($_POST['zip_list'] as $selected)
			{
			$zip->addFile($selected);
			}
			echo"<h3>Selected files are successfully zipped</h3>";
		}
		else
		{
			echo"Select atleast one";
		}
	$zip->close();
	}
}
?>

In the above script,

  1. Multiple files are being chosen by the user and upload action is performed.
  2. Then the user is asked to choose the files he/she wants to zip.
  3. Then the selected files are zipped under the file name newzip.zip

The user interface of the script is as follows,

compress and create zip archive in PHP

 

The output of the script is as follows,

output of the PHP Script

This is how we can create and compress zip files using PHP. If any doubts are there, comment down below,

See also,

Leave a Reply

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