How To Create Zip File Using Ziparchive in Laravel

In this tutorial I will show you how to create zip file using ziparchive in laravel 6, laravel 7, laravel 8. Some times client's have requirments to have functionalities like create zip file for documantation or images and download it. So, at that time we can find many laravel packeges to perform this task but here, I am show you to how to create zip file in laravel using ziparchive without any packege. 

Laravel provide ZipArchive class for create zip file in laravel. So, I will use ZipArchive in laravel 6, laravel 7 and laravel 8. In  laravel you can create zip file and download it. So, for this example we are not use any zip file package for create zip file in laravel 6/7/8.

So, let's see example of how to create zip file using ziparchive in laravel 6, laravel 7 and laravel 8.

 

 

In below code I have created one function in laravel controller and added ZipArchive class.

Note : I have created  Zipfile_Example folder in public folder and added some images. So, you need to also create one folder and add some file also.

 

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use ZipArchive;

public function ZipArchiveExample()
{                                
    $zip = new ZipArchive;

    $fileName = 'Zipfile_Example.zip';

    if ($zip->open(public_path($fileName), ZipArchive::CREATE) === TRUE)
    {
        $files = \File::files(public_path('Zipfile_Example'));

        foreach ($files as $key => $value) {
            $file = basename($value);
            $zip->addFile($value, $file);
        }
         
        $zip->close();
    }

    return response()->download(public_path($fileName));
}

 


You might also like :

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS