Compress Folder Into ZIP and Download Without Saving ZIP File In Server
Wednesday, March 6, 2024
In web development, the need to compress multiple files or a folder into a single ZIP file often arises, especially when dealing with large amounts of data. Additionally, providing users with the ability to download these ZIP files directly without cluttering the server with temporary files is a common requirement. To address these needs, we've developed a simple and efficient PHP library that streamlines the process of compressing folders into ZIP files and facilitates their direct download without server-side storage.
Overview
Our PHP library utilizes the powerful ZipArchive class to create and manage ZIP archives. The key feature of this library is its ability to compress an entire folder of files into a single ZIP file on the fly and then serve it directly to users for download via the web browser.
Usage
Using our library is straightforward. Simply include it in your PHP project and follow these simple steps:
- Define the path to the folder you want to compress.
- Initialize the ZIP archive and add files from the specified folder.
- Set appropriate HTTP headers to initiate the download.
- Output the ZIP file content directly to the user's browser.
- Optionally, delete the temporary ZIP file after download to maintain server cleanliness.
<?php $zip_file = "./files/all-image.zip"; touch($zip_file); $zip = new ZipArchive; $this_zip = $zip->open($zip_file, ZipArchive::CREATE); if ($this_zip) { $folder = opendir('./images'); if ($folder) { while (false !== ($image = readdir($folder))) { if ($image !== "." && $image != "..") { $file_with_path = "./images/" . $image; $zip->addFile($file_with_path, $image); } } closedir($folder); } $zip->close(); if (file_exists($zip_file)) { $zip_file_name = "download.zip"; header("Content-type: application/zip"); header("Content-Disposition: attachment; filename=" . $zip_file_name); header("Content-Length: " . filesize($zip_file)); readfile($zip_file); unlink($zip_file); } } ?>
Conclusion
With our PHP library, you can effortlessly compress folders into ZIP files and provide users with a seamless downloading experience without cluttering your server. Whether you're handling image galleries, document repositories, or any other file-centric application, our library simplifies the process and enhances user satisfaction.
git repo - https://github.com/iamvirul/compress-folder-into-zip-and-download-without-saving-zip-file