Create and download a Zip file using PHP

To construct a Zip file, PHP has the ZipArchive class. Making files is simpler with this class.

When getting ready a collection of files and folders for download, programming is primarily needed for Zip generation.

The function I'm writing in the example will read every file and folder in the given directory and add them to the ZipArchive class object.

INSTRUCTION

HTML

Making a <form> with two button elements: a "create zip" button and a "download" button.

<div class='container'>
<h2>Create and Download Zip file using PHP</h2>
<form method='post' action=''>
<input type='submit' name='create' value='Create Zip' />&nbsp;
<input type='submit' name='download' value='Download' />
</form>
</div>

PHP

Within the project, I've established an included folder where I've put several files and directories.

Create Zip

For the production of Zip files, create a ZipArchive Class object. Define a function called createZip() that can read files and directories from the directory path provided.

If file

If the reading value is a file, use the addFile() function to add the file to the zip object.

If directory

If the value is a directory, make a new, empty directory and use the directory path to invoke the createZip() method.

Download Zip

Verify the zip file's existence. If it does, download it and delete it from the server.

Below is the completed PHP code:

// Create ZIP file
if(isset($_POST['create'])){
$zip = new ZipArchive();
$filename = "./myzipfile.zip";
if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
exit("cannot open <$filename>n");
}
$dir = 'includes/';
// Create zip
createZip($zip,$dir);
$zip->close();
}
// Create zip
function createZip($zip,$dir){
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
// If file
if (is_file($dir.$file)) {
if($file != '' && $file != '.' && $file != '..'){
$zip->addFile($dir.$file);
}
}else{
// If directory
if(is_dir($dir.$file) ){
if($file != '' && $file != '.' && $file != '..'){
// Add empty directory
$zip->addEmptyDir($dir.$file);
$folder = $dir.$file.'/';
// Read data of the folder
createZip($zip,$folder);
}}}}
closedir($dh);
}}}
// Download Created Zip file
if(isset($_POST['download'])){
$filename = "myzipfile.zip";
if (file_exists($filename)) {
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Content-Length: ' . filesize($filename));
flush();
readfile($filename);
// delete file
unlink($filename);
}}

Conclusion

The directory path is a parameter that the function createZip(), which was previously defined, accepts. The path's files and folders will all be read, and everything will be added to the zip file.

To unzip the Zip file, you may also utilize the ZipArchive Class. That's it, hope it's helpful.

Similar Tutorials

Comments