PHP tutorial- AJAX


Create zip file using ZipArchive



In PHP, it is possible to create a zip file that contains multiple files and send the zip file to the browser for download. A convenient class provided by PHP to achieve this goal is called ZipArchive. To create a zip file with the ZipArchive class, first you need to create an object of the ZipArchive. Then you can use the open(string zip_name, int flag) method to open the zip file for reading, writing or modifying. The zip_name is the zip file name. The flag can be one of the followings:

-ZipArchive::OVERWRITE

-ZipArchive::CREATE

-ZipArchive::EXCL

-ZipArchive::CHECKCONS

The ZipArchive::OVERWRITE flag allows you to override the zip file if it already exists. By using the ZipArchive::CREATE flag, PHP creates the zip file for you if it doesn't exist. Th ZipArchive::EXC flag will shows an error if the file already exists. The ZipArchive::CHECKCONS performs additional consistency checks on the archive, and error if they fail.

After the zip file is successfully opened, you can use the addFile(string file_path, string file_name) method to add files to the zip file. In the example code below, all PDF files in myfolder directory are added to the zip file. Then the zip file is sent to the browser for download.

<?php
//create ZipArchive object
$zip = new ZipArchive();
$archive_file_name="myzip.zip";
//create the zip file
if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
exit("cannot open <$archive_file_name>\n");

}

//retrieve files from the myfolder directory and add them to the zip file
$sdi="./myfolder/";
$list=scandir($sdi);
foreach($list as $value)
{
$x=explode(".",$value);
if($x[1]=="php") {
$zip->addFile($sdi.$value,$value);
echo $value."<br/>";
}

}
//close the zip file
$zip->close();
//send the zip file to browser
if(file_exists($archive_file_name)){
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$archive_file_name");
readfile($archive_file_name);
//unlink($archive_file_name);
}

?>

create zip archive in php




Comments





This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.