03-Apr-2023
.
Admin
Hi Dev,
In this example, I will show you php create zip file and download example. if you want to see example of how to generate zip file and download example in php? then you are a right place. I would like to share with you php create zip file and download example. This article will give you simple example of how to save zip file and download in php?.
In this example to create and downlode zip file in php. in the example, we will use open(), addFile() and close() to create a zip file.Let's see example with output.
Example :
index.php
<?php
$file_names = array('demo1.jpg','demo2.jpg');
// Downlode File Name
$archive_file_name=$name.'index.zip';
zipFilesAndDownload($file_names,$archive_file_name,$file_path);
function zipFilesAndDownload($file_names,$archive_file_name)
{
//echo $file_path
$zip = new ZipArchive();
//create the file and throw the error if unsuccessful
if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
exit("cannot open <$archive_file_name>\n");
}
//add each files of $file_name array to archive
foreach($file_names as $files)
{
$zip->addFile($file_path.$files,$files);
}
$zip->close();
//then send the headers to force download the zip file
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$archive_file_name");
header("Pragma: no-cache");
header("Expires: 0");
readfile("$archive_file_name");
}
?>
Output:
After run successfully above example, you will see Zip file saved in your directory by index.zip Name.
I hope it could help you...
#PHP