00 Votes

PHP: GZip compress files with PHP

Tip by Computer Expert | 2012-08-12 at 23:53

Using this little PHP script, you can compress all files with a certain file extension (adjust it in the first line) with GZip:

$files = glob('*.js');
 
foreach($files as $file) {
   $fil = basename($file);
   $filgz = $fil.'.gz';
   file_put_contents($filgz, gzencode(file_get_contents($fil), 9));
}

All files that are saved in the same folder like the script file, will be compressed. First, in $files, an array containing a list of all files will be created. Then, file for file will be compressed and saved with the extension .gz.

The example converts all JavaScript files with the extension .js. If we want to compress other files, for example CSS files, we only need to modify the script in the first line and change the '*.js' to '*.css'

The script is especially useful if we want to offer the compressed files as an alternative to the uncompressed files to reduce the loading time of a web page. The exact procedure for this is described in detail in this tutorial.

ReplyPositiveNegative
00 Votes

My little tip:

If you want to combine several files as a single compressed file, you can specify this as a parameter for file_put_contents.

In the example above that would be:

file_put_contents($datgz, gzencode(file_get_contents($dat), 9), FILE_APPEND);
2020-08-24 at 15:18

ReplyPositive Negative
Reply

About the Author

AvatarThe author has not added a profile short description yet.
Show Profile

 

Related Topics

Program in ZIP-Folder

Info | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.