How to Create Zip Folder and Download in PHP - TechvBlogs
PHP

How to Create Zip Folder and Download in PHP

In this article, You will learn How to Create Zip Folder and Download in PHP.


Smit Pipaliya - Author - TechvBlogs
Smit Pipaliya
 

2 months ago

TechvBlogs - Google News

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:

  1. demo1.jpg
  2. demo2.jpg

Executing the Code:

  1. Copy the provided index.php file.
  2. Place the two image files (demo1.jpg and demo2.jpg) in proximity to the index.php file.
  3. 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!

PHP

Comments (0)

Comment


Note: All Input Fields are required.