How to gzip folder in laravel project?

by cali_green , in category: Third Party Scripts , 5 months ago

How to gzip folder in laravel project?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by larissa , 5 months ago

@cali_green 

To gzip a folder in a Laravel project, you can use the ZipArchive class provided by PHP. Here's an example of how you can achieve this:

  1. First, create a new controller (e.g., GzipController) in your Laravel project.
1
php artisan make:controller GzipController


  1. Open the GzipController.php file and add the following method to compress a folder using the ZipArchive class:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
use ZipArchive;
use IlluminateHttpRequest;

public function gzipFolder(Request $request)
{
    $dir = public_path('folder-to-gzip'); // specify the folder to be gzipped

    $zipFile = public_path('compressed-folder.zip'); // path of the output gzipped file

    $zip = new ZipArchive;
    if ($zip->open($zipFile, ZipArchive::CREATE) === TRUE) {
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
        foreach ($files as $file) {
            $filePath = $file->getRealPath();
            $relativePath = substr($filePath, strlen($dir) + 1);
            if (is_file($filePath)) {
                $zip->addFile($filePath, $relativePath);
            }
        }
        $zip->close();
        return response()->download($zipFile)->deleteFileAfterSend(true);
    } else {
        return response()->json(['message' => 'Failed to create compressed file'], 500);
    }
}


  1. Create a route in your routes/web.php file to access the gzipFolder method in your GzipController:
1
Route::get('/gzip-folder', 'GzipController@gzipFolder');


  1. Finally, you can access the gzipFolder method by visiting the /gzip-folder route in your Laravel project. This will compress the specified folder and prompt the user to download the gzipped file.


Please make sure to replace folder-to-gzip with the path of the folder you want to gzip and compressed-folder.zip with the desired output gzipped file name.