How To Create Zip File Using Ziparchive in Laravel

Websolutionstuff | Sep-16-2020 | Categories : Laravel PHP

In this article, we will see how to create a zip file using zipArchive in laravel. Sometimes we have requirements to have functionalities like creating zip files for documentation or images and downloading them. So, at that time we can find many laravel packages to perform this task. But here, we will see how to create a zip file in laravel using zipArchive without any package. 

Laravel provides ZipArchive class for creating zip files in laravel. So, we will use ZipArchive in laravel 6 and laravel 7, and laravel 8.

How To Create Zip File In Laravel Using zipArchive

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

Note: I have created a Zip_Example folder in the public folder and added some images. So, you need to also create one folder and add some files also.

 

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use ZipArchive;

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

    $fileName = 'Example.zip';

    if ($zip->open(public_path($fileName), ZipArchive::CREATE) === TRUE)
    {
        $files = \File::files(public_path('Zip_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:

Recommended Post
Featured Post
How To Store JSON Data In Database Laravel 9
How To Store JSON Data In Data...

In this article, we will see how to store JSON data in the database laravel 9. Laravel 9 stores JSON data in M...

Read More

Sep-28-2022

How To Validate Phone Number Using jQuery
How To Validate Phone Number U...

In this article, we will see how to validate phone numbers using jquery. We will learn different methods of validat...

Read More

Oct-24-2022

Angular 13 Crop Image Before Upload With Preview
Angular 13 Crop Image Before U...

In this article, we will see the angular 13 crop image before uploading with a preview. we will give you a sim...

Read More

May-10-2022

How to Convert PDF to Image in Laravel 10
How to Convert PDF to Image in...

Greetings, Laravel enthusiasts! Today, let's unravel a common challenge in web development – converting PDFs t...

Read More

Dec-22-2023