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:





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.

//create ZipArchive object
$zip = new ZipArchive();
//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
foreach($list as $value)
if($x[1]=="php") {
echo $value."<br/>";

//close the zip file
//send the zip file to browser
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");


create zip archive in php


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.