Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
How to Create Zip of File or Folder in Laravel

How to Create Zip of File or Nested Folder in Laravel ?

Aman Jain, May 22, 2022May 24, 2022

Zip files are used to create lossless data compression and store multiple files folder in single file. In laravel create zip of file or nested folder laravel can be archived by ZipArchive library,its gives easy to use flexibilities to developers so they can easily integrate the Zip creation activity in the project. So in this article i will show you to create zip of file or folder in laravel of multiple files and folder in single file then easily download or store at server path.

In this article i will use PHP ZipArchive library to create the zip. This library has several methods to open, create , extract, add, setPath, delete and many more. But in this topic we will cover creating the zip file and add the files and folder to the zip.

In this example we will create a simple example to add the files and nested folder to zip file in laravel . For this we will create a controller, files and zip.

Let’s start Create Zip of File or nested Folder in Laravel with simple step by step

Step 1: Create a fresh laravel project

Open a terminal window and type below command to create a new project

composer create-project --prefer-dist laravel/laravel blog

You can also read this to start with new project

Step 2 : Create controller

Let’s create a controller and add method createZip

php artisan make:controller ZipController

and add the below code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use ZipArchive;
class ZipController extends Controller
{
    
   
    function createZip(){

        //save to server 
        $fileName = time().rand(111111111,9999999999).'_invoice.zip';
        $destinationPath= '/uploads/zip';
        $storageDestinationPath= storage_path("app$destinationPath");
       
        if (!\File::exists( $storageDestinationPath)) {
            \File::makeDirectory($storageDestinationPath, 0755, true);
        }

        $zip = (new ZipArchive());
        $isOpened =  $zip->open($storageDestinationPath."/".$fileName, ZipArchive::CREATE | \ZipArchive::OVERWRITE);
        if($isOpened === TRUE){
            $this->addToZip(
                $zip,[

                    storage_path("app/uploads/images/16526291274723877395.jpg"),
                    storage_path("app/uploads/images/thumbs"),
                    storage_path("app/uploads/images/16526317155446630681.jpeg"),
                    storage_path("app/uploads/images/thumbs/50x50"),
                ],
                "invoices"
                );

            $zip->close();
            
            return response()->download($storageDestinationPath."/".$fileName,"invoices.zip");
        }   
        else{
            return response()->html("Unbale to create/open zip");
        } 

    }

    function createZipInFLy(){

        
        //in the fly without storing to server
        $fileName = @tempnam("tmp", "zip");
        
         
        $zip = (new ZipArchive());
        $isOpened =  $zip->open($$fileName, ZipArchive::CREATE | \ZipArchive::OVERWRITE);
        if($isOpened === TRUE){
            $this->addToZip(
                $zip,[

                    storage_path("app/uploads/images/16526291274723877395.jpg"),
                    storage_path("app/uploads/images/thumbs"),
                    storage_path("app/uploads/images/16526317155446630681.jpeg"),
                    storage_path("app/uploads/images/thumbs/50x50"),
                ],
                "invoices"
                );

            $zip->close();
            
            return response()->download($fileName,"invoices.zip");
        }   
        else{
            return response("Unbale to create/open zip");
        } 

    }


    function addToZip($zip,$filesArray,$fileName=''){
        $dir='';
        if($fileName!=''){
            $fileName = str_replace(".zip","",$fileName);
            $zip->addEmptyDir($fileName); 
            $dir=$fileName."/";
        }
        foreach($filesArray as $k=>$path){
             
            $isFile =  \File::isFile($path);
            if($isFile){
                $file = new \SplFileInfo($path);
                $zip->addFile($file->getPathname(),$dir.$file->getFilename());
            }
            else{
                $it = new \RecursiveDirectoryIterator($path);
                $repalcer=dirname($it->getPath());;
                foreach(new \RecursiveIteratorIterator($it) as $file)
                { 
                    if(!$file->isDir()){
                        $zip->addFile($file->getPathname(),"$dir".str_replace($repalcer."/","",$file->getPathname()));
                    }
                }
            }
            
        }
         
    }

}

In above code First of all we are checking the directory is exist or not then if not available then we are creating the directory at the location.

Then using ZipArchive library we are creating the zip file and opened successfully then we have created another method which is addToZip to handle the logic to add the multiple files and folder to zip file. it accepts ZipArchive object, second array of files and folder and third name of zip file as below


function addToZip($zip,$filesArray,$fileName=''){
        $dir='';
        if($fileName!=''){
            $fileName = str_replace(".zip","",$fileName);
            $zip->addEmptyDir($fileName); 
            $dir=$fileName."/";
        }
        foreach($filesArray as $k=>$path){
             
            $isFile =  \File::isFile($path);
            if($isFile){
                $file = new \SplFileInfo($path);
                $zip->addFile($file->getPathname(),$dir.$file->getFilename());
            }
            else{
                $it = new \RecursiveDirectoryIterator($path);
                $repalcer=dirname($it->getPath());;
                foreach(new \RecursiveIteratorIterator($it) as $file)
                { 
                    if(!$file->isDir()){
                        $zip->addFile($file->getPathname(),"$dir".str_replace($repalcer."/","",$file->getPathname()));
                    }
                }
            }
            
        }
         
}

Here if filename is provided the we are first creating a directory with same name then checking the file type if its a file then adding it to zip else directory then we are using RecursiveDirectoryIterator to process the nested folder to add into the zip.

Create and Download zip file in the fly

By creating the file in temp folder we can download the zip without saving to the server for long time so we have create this method

function createZipInFLy(){

        
        //in the fly without storing to server
        $fileName = @tempnam("tmp", "zip");
        
         
        $zip = (new ZipArchive());
        $isOpened =  $zip->open($$fileName, ZipArchive::CREATE | \ZipArchive::OVERWRITE);
        if($isOpened === TRUE){
            $this->addToZip(
                $zip,[

                    storage_path("app/uploads/images/16526291274723877395.jpg"),
                    storage_path("app/uploads/images/thumbs"),
                    storage_path("app/uploads/images/16526317155446630681.jpeg"),
                    storage_path("app/uploads/images/thumbs/50x50"),
                ],
                "invoices"
                );

            $zip->close();
            
            return response()->download($fileName,"invoices.zip");
        }   
        else{
            return response()->html("Unbale to create/open zip");
        } 

    }

Step 3: Create two routes in routes/web.php

One route for save the zip to the server as well download and other to download in the fly without saving to server.

routes/web.php

<?php

use App\Http\Controllers\ZipController;
use Illuminate\Support\Facades\Route;

Route::get("/create-zip",[ZipController::class,"createZip"]);
Route::get("/create-zip-fly",[ZipController::class,"createZipInFLy"]);

I

Results Screenshot:

create zip laravel
create zip laravel
Screenshot 2022 05 22 at 12.36.57 PM

I hope it will help you to implement to create zip file with files and folders. you can also read article to How to Import or Convert Excel/CSV to HTML in laravel 8 / 9?

Related

Php Laravel Laravel 9 compressionfilesfolderlaravelzip

Post navigation

Previous post
Next post

Related Posts

Php How to fetch Soft Deleted Records in Laravel 9

How to Fetch Soft Deleted Records in Laravel ?

June 17, 2022June 21, 2022

In this article we will learn to fetch soft deleted records in Laravel. In our recent article Use Soft Delete to Temporary (Trash) Delete the Records in Laravel ? we learnt to delete the file without actually deleting from database and sometimes we want to show records that are soft…

Read More
Php Laravel CRUD with Search, Image and Pagination

Laravel 10 CRUD Example Tutorial with Search, Image and Pagination

March 12, 2023July 3, 2024

This article will cover the implementation of CRUD operations along with Search, Image uploading, and Pagination in Laravel. In addition to CRUD operations, we will also cover form validation, unique validation, Flash messages, and viewing uploaded images. It is crucial to learn all aspects of CRUD and beyond, including uploading…

Read More
Php How to Change Date Format in Blade View File in Laravel

How to Change Date Format in Blade View File in Laravel ?

September 8, 2022March 16, 2024

Laravel default shows the date in the way its stored in database bu sometimes we want to change date format in blade view file in laravel according to our requirements. It can be multiple possibilities and requirement from client or product manager to change the date format so in this…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • August 2025
  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • The Transformative Power of Education in the Digital Age
  • Understanding High Vulnerabilities: A Closer Look at the Week of July 14, 2025
  • Exploring Fresh Resources for Web Designers and Developers
  • The Intersection of Security and Technology: Understanding Vulnerabilities
  • Mapping Together: The Vibrant Spirit of OpenStreetMap Japan
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version