Create a Zip File Using PHP and Download Multiple Files


Demo Download

Today I am sharing how to create a zip file of multiple files using PHP and download that zip file on click. For this purpose I will need a folder where all files are available which can be selected and downloaded. I will also create a single php page which contain the following scripts.

HTML

Create a simple PHP page and copy paste the below form.

<form name="zips" action="" method="post">
<input type="checkbox" id="checkAll" />
<label>Select All</label><br />
<input class="chk" type="checkbox" name="files[]" value="SampleFile.pdf"/>
<label>PDF File</label><br />
<input class="chk" type="checkbox" name="files[]" value="SampleFile.docx"/>
<label>Word File</label><br />
<input class="chk" type="checkbox" name="files[]" value="AllPHPTricks.png"/>
<label>Image File</label><br />
<input type="submit" id="submit" name="createzip" value="Download All Seleted Files" >
</form>

jQuery

Add the following script in footer of web page. Don’t forget to add jQuery library before this script.

$('#submit').prop("disabled", true);
$("#checkAll").change(function () {
      $("input:checkbox").prop('checked', $(this).prop("checked"));
	  $('#submit').prop("disabled", false);
	  if ($('.chk').filter(':checked').length < 1){
			$('#submit').attr('disabled',true);}
});

$('input:checkbox').click(function() {
        if ($(this).is(':checked')) {
			$('#submit').prop("disabled", false);
        } else {
		if ($('.chk').filter(':checked').length < 1){
			$('#submit').attr('disabled',true);}
		}
});

As you can see above that when you click on select all, all checkboxes are checked or unchecked. You can see my tutorial about how to select deselect all checkboxes using jquery.

PHP

Copy paste the below PHP script in the top of web page. When someone submit form first we are checking if files array is set or not, then we are creating zip file and downloading that file.

<?php
if(isset($_POST['files']))
{
$error = ""; //error holder
if(isset($_POST['createzip']))
{
$post = $_POST; 
$file_folder = "files/"; // folder to load files
if(extension_loaded('zip'))
{ 
// Checking ZIP extension is available
if(isset($post['files']) and count($post['files']) > 0)
{ 
// Checking files are selected
$zip = new ZipArchive(); // Load zip library 
$zip_name = time().".zip"; // Zip name
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE)
{ 
 // Opening zip file to load files
$error .= "* Sorry ZIP creation failed at this time";
}
foreach($post['files'] as $file)
{ 
$zip->addFile($file_folder.$file); // Adding files into zip
}
$zip->close();
if(file_exists($zip_name))
{
// push to download the zip
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zip_name.'"');
readfile($zip_name);
// remove zip file is exists in temp path
unlink($zip_name);
}

}
else
$error .= "* Please select file to zip ";
}
else
$error .= "* You dont have ZIP extension";
}
}
?>

I have shared another detailed tutorial on how to create a zip file in PHP. It contains more details with more examples that will help you to get your desired results.

Demo Download

If you found this tutorial helpful so share it with your friends, developer groups and leave your comment.

Facebook Official Page: All PHP Tricks

Twitter Official Page: All PHP Tricks

Article By
Javed Ur Rehman is a passionate blogger and web developer, he loves to share web development tutorials and blogging tips. He usually writes about HTML, CSS, JavaScript, Jquery, Ajax, PHP and MySQL.
  1. Hi, thanks by the post.
    i’m a beginner in php… i was able to put your example to work, but when i put it in my project, it doesn’t work. after downloading the file, when i trie to open it, it says file invalid.
    I opened it in notepad++ and i saw it has the html code of all the page in side it.
    if I remove all that code, the file opens correctly…
    how can I make the zip without de html code?

    1. Dear Simon, this tutorial is focused on files that are available on website server not on PC.
      When the files are available on website server then you can not use any online tool for it, you will need to create a ZIP file using a PHP script.

  2. Hi, How do we achieve this without the tick boxes to select the files, and instead just download all the files in the folder?. Can we give custom path to the folder?

  3. Its working fine on Localhost but not on the server need your help.

    if($_GET[‘staff_id’])
    {
    $error = “”; //error holder
    $staff_row = Get_Row(“tbl_staff”,”id”,$_GET[‘staff_id’]);

    //$post = $_POST;
    $file_folder = “uploads/documents/”; // folder to load files
    if(extension_loaded(‘zip’))
    {
    // Checking ZIP extension is available
    $zip = new ZipArchive(); // Load zip library
    $zip_name = time().”.zip”; // Zip name
    if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE)
    {
    // Opening zip file to load files
    $error .= “* Sorry ZIP creation failed at this time”;
    }

    $Sql = “select * from tbl_staff_documents where staff_id='”.$_GET[‘staff_id’].”‘ “;
    $Sql.= ” order by id DESC “;
    $query = @mysql_query($Sql);
    while($Rows = @mysql_fetch_assoc($query))
    {
    // Checking files are selected
    $file = $Rows[‘documents’];
    $zip->addFile($file_folder.$file); // Adding files into zip
    }
    $zip->close();
    if(file_exists($zip_name))
    {
    // push to download the zip
    header(‘Content-type: application/zip’);
    header(‘Content-Disposition: attachment; filename=”‘.$zip_name.'”‘);
    readfile($zip_name);
    // remove zip file is exists in temp path
    unlink($zip_name);
    }
    }
    else
    {
    $error.= “* You dont have ZIP extension”;
    }
    }

  4. Is there a good detailed reference link or “How To” on how to get this ZipArchive library working on PHP7.0 ?

  5. Hi,
    I think there is a small error in the code:

    if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE)

    should be:
    if($zip->open($zip_name, ZIPARCHIVE::CREATE)==TRUE)

  6. thanks for the great tutorial!

    But I have issue, it’s not extracting properly on mac version.

    Please help.

      1. Hi, I used this code, but getting error that ZipArchive not found, can you please provide this file.

  7. Hi,
    great tutorial, would it be also possible to make another submit button which would send this zip file as email?

  8. $(‘#submit’).prop(“disabled”, true);
    $(“#checkAll”).change(function () {
    $(“input:checkbox”).prop(‘checked’, $(this).prop(“checked”));
    $(‘#submit’).prop(“disabled”, false);
    if ($(‘.chk’).filter(‘:checked’).length < 1){
    $('#submit').attr('disabled',true);}
    });

    $('input:checkbox').click(function() {
    if ($(this).is(':checked')) {
    $('#submit').prop("disabled", false);
    } else {
    if ($('.chk').filter(':checked').length < 1){
    $('#submit').attr('disabled',true);}
    }
    });

    ehat is libarary of this code ?

  9. Can i use this code in wordpress for downloading? Is working good on localhost, but when i try in wordpress, don’t zip anything… Pls Help

    1. WordPress is a CMS, it has its own framework so you will need to implement according to its framework, this tutorial is not focused on WP. You have to follow WP guidance to create zip and download.

  10. I am having trouble getting the download to work. I have tried it on different servers using php5.2, 5.6 and 7.0. The php5.2 is working well, but not the other php. Do you know if there are any deprecated items in your script for php7.0 which is the final server?

    1. Hi Jesse, well i have not tested this script on PHP 7.0 so i am not sure if it will work on it or not. But you can see that i am using here the following:
      extension_loaded() function and new ZipArchive() Load zip library, make sure these both are enabled on your PHP 7.0 Version.

  11. Just what I am looking for!
    And no javascript…yay

    However the php is being stripped from my page. Would that be a server setting? What version of php does the script need on the server?

    thanks

Leave a Reply

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