Unlock the power of PHP's ZipArchive to effortlessly create and distribute zip files for seamless downloads. In this guide, we'll delve into a step-by-step process, ensuring you master the art of zip file creation using a user-friendly approach.
Understanding the Basics of Zip File Creation
Crafting a Simple PHP Function: createZip()
To initiate the zip file creation process, we introduce a straightforward PHP function named createZip()
. This function proves to be a versatile tool, allowing you to effortlessly compress and bundle various files, be it images, documents, or any other essentials.
<?php
/* create a compressed zip file */
function createZip($files = array(), $destination = '', $overwrite = false) {
if(file_exists($destination) && !$overwrite) { return false; }
$validFiles = [];
if(is_array($files)) {
foreach($files as $file) {
if(file_exists($file)) {
$validFiles[] = $file;
}
}
}
if(count($validFiles)) {
$zip = new ZipArchive();
if($zip->open($destination, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
foreach($validFiles as $file) {
$zip->addFile($file, $file);
}
$zip->close();
return file_exists($destination);
} else {
return false;
}
}
$fileName = 'my-archive.zip';
$files_to_zip = ['demo1.jpg', 'demo2.jpg'];
$result = createZip($files_to_zip, $fileName);
header("Content-Disposition: attachment; filename=\"".$fileName."\"");
header("Content-Length: ".filesize($fileName));
readfile($fileName);
?>
Step-by-Step Guide to Executing the Code
Prerequisites:
Ensure that you have two image files, namely:
demo1.jpg
demo2.jpg
Executing the Code:
- Copy the provided
index.php
file. - Place the two image files (
demo1.jpg
anddemo2.jpg
) in proximity to theindex.php
file. - Run the entire code snippet.
Conclusion
By following this comprehensive guide, you've successfully acquired the skills to create a zip file using PHP's ZipArchive. This efficient process allows you to package and distribute files seamlessly, enhancing user experience and file management. Feel free to incorporate this functionality into your projects for a smoother download experience!