Search code examples
phplaravellaravel-5gziparchive

How to gzip folder in Laravel project


I want to compress folder and it's content in Laravel project into gzip archive with highest possible compression level.

storage_path().'myFolder'

It's not meant to be transferred over HTTP so please don't get confused with server response gzip compression.

I just want an archive but didn't find info whether Laravel has any tool for the prurpose, any ideas?


Solution

  • Here's a helper function for you.

    if (!function_exists('gzip')) {
        function gzip($filename, $disk = 'local', $delete_original = false)
        {
            $disk = Storage::disk($disk);
            $data = $disk->get($filename);
            $out_file = "$filename.gz";
    
            $gzdata = gzencode($data, 9);
            $disk->put($out_file, $gzdata);
            $fp = fopen($disk->path($out_file), "w");
            $result = fwrite($fp, $gzdata);
            fclose($fp);
    
            if ($result && $delete_original) {
                $disk->delete($filename);
            }
    
            return $result > 0;
    
        }
    }
    

    Tested and working for me on laravel 7.x. Just make sure you have gzip compression enabled on your machine.

    enter image description here