Compressing Multiple Files as Zip and Download it using PHP

In this tutorial, you will learn how to Compress Multiple Files as Zip and Download it using PHP Language. The tutorial aims to provide IT/CS Students and new programmers with a reference on using PHP ZipArchive(). Here, I will be providing a simple web application's snippets and source code zip file which demonstrates our main objective in this tutorial.

What is Zip File?

One or more compressed files or directories may be present in a ZIP file. It is an archive format for lossless data compression and one of the most widely used compression formats in the world.

What is PHP ZipArchive?

The ZipArchive is a class in PHP that contains multiple methods used to perform several zipping operations. It is used for adding new files/directories, extracting, opening, and closing ziparchive content.

PHP ZipArchive Syntax?

The snippet below is an example of how to use the PHP ZipArchive.

  1. <?php
  2. $zip = new ZipArchive();
  3. /**
  4. * ZipArchive Flags
  5. * - ZipArchive::OVERWRITE
  6. * - ZipArchive::CREATE
  7. * - ZipArchive::RDONLY
  8. * - ZipArchive::CHECKONS
  9. */
  10. $zip->open("zip_filename.zip", [ZipArchive Flags])
  11.  
  12. $zip->close();

How to Compress Multiple Files as Zip and Download it in PHP?

Here are the following snippets or source code of a simple web application written in PHP and HTML that demonstrates file compressions using ZipArchive and Download the created Zip file.

First, create a new directory named uploads in your source code directory. Add some sample files inside the directory to use on this sample web application.

Interface

Next, create a new PHP file and save it as index.html. The file contains the following script. The snippet below is a combined script of HTML and PHP for displaying the page interface, form, and list of files. Note that the snippet below loads the Bootstrap Framework using CDN which needs you to be connected to the internet to display the page design properly.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="UTF-8">
  4. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>ZIP multiple files and Download - PHP</title>
  7. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  8. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  9. <link rel="stylesheet" href="style.css">
  10.  
  11. <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  12. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  13. </head>
  14. <body style="background:#e1ecf7">
  15. <nav class="navbar navbar-expand-lg navbar-dark" style="background:#1597BB">
  16. <div class="container">
  17. <a class="navbar-brand" href="./">ZIP multiple files and Download - PHP</a>
  18. <div>
  19. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  20. </div>
  21. </div>
  22. </nav>
  23. <div class="container-fluid px-5 my-3 pt-5">
  24. <div class="col-lg-6 col-md-8 col-sm-12 mx-auto">
  25. <h3 class="text-center">Compress Multiple Files as ZIP and Download it using PHP</h3>
  26. <hr>
  27. <div class="card rounded-0">
  28. <div class="card-header rounded-0">
  29. <div class="card-title">List of Files</div>
  30. </div>
  31. <div class="card-body rounded-0">
  32. <div class="container-fluid">
  33. <form action="zip_and_download.php" id="download-form" method="POST">
  34. <div class="list-group">
  35. <?php
  36. $scandir = scandir("uploads/");
  37. $i = 1;
  38. foreach($scandir as $file):
  39. if(in_array($file, ['.', '..']))
  40. continue;
  41. ?>
  42. <div class="list-group-item">
  43. <div class="d-flex w-100">
  44. <div class="col-auto">
  45. <div class="form-check">
  46. <input class="form-check-input" type="checkbox" name="fileName[]" value="<?= $file ?>" id="file_<?= $i ?>">
  47. </div>
  48. </div>
  49. <div class="col-auto flex-shrink-1 flex-grow-1"><?= $file ?></div>
  50. </div>
  51. </div>
  52. <?php
  53. $i++;
  54. endforeach;
  55. ?>
  56. </div>
  57. </form>
  58. </div>
  59. </div>
  60. <div class="card-footer py-2 text-center">
  61. <button class="btn btn-primary rounded-pill col-lg-4 col-md-6 col-sm-12 col-xs-12" form="download-form"><i class="fa-solid fa-download"></i> Download Selected</button>
  62. </div>
  63. </div>
  64. </div>
  65. </div>
  66. </body>
  67. </html>

PHP API

Then, create a new PHP file and save it as zip_and_download.php. The file contains the following snippet. The snippet is a PHP script for creating a zip file containing the compressed files selected from the form on the main page and automatically or forcing the page to download the created zip file.

  1. <?php
  2. if($_SERVER['REQUEST_METHOD'] == "POST"){
  3. //Zip filename
  4. $zip_fname = "compressed_zip_file.zip";
  5. //Removing the file if already exist
  6. if(is_file($zip_fname))
  7. unlink($zip_fname);
  8.  
  9. // Load the ZipArchive Class
  10. $zip = new ZipArchive();
  11.  
  12. //Opening/Create a new zip archive
  13. if ($zip->open($zip_fname, ZIPARCHIVE::CREATE )!==TRUE) {
  14. die("Can't open {$zip_fname} file.");
  15. }
  16.  
  17. // Adding the selected files to the archive
  18. foreach($_POST['fileName'] as $file)
  19. {
  20. $zip->addFile("uploads/".$file, $file);
  21. }
  22. //closing the zip
  23. $zip->close();
  24.  
  25.  
  26. //Force to download the created zip file
  27. header("Content-type: application/zip");
  28. header("Content-Disposition: attachment; filename=$zip_fname");
  29. header("Pragma: no-cache");
  30. header("Expires: 0");
  31. readfile("$zip_fname");
  32. }

Snapshots

Here are some of the application's snapshots.

Zip multiple Files and Download using PHP

Zip multiple Files and Download using PHP

There you go! You can now test the application on your end and see if it achieves our main objective for the tutorial which is to compress multiple files into a zip file and download it. I have also provided the complete source code zip file that I created for this tutorial. You can download it by clicking the Download Button located below this article.

That's the end of this tutorial. I hope this Compressing Multiple Files as Zip and Download it using PHP Tutorial helps you with what you are looking for and that you'll find this useful for your current and future PHP Projects/.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding:)

Add new comment