Wednesday, August 29, 2018

Creating a GZip Archive on Your PHP Server to Serve to Web Users

Gzip is a popular zip-archive format for storing files in the long-term. Users benefit from this by reducing the download time, or by being able to group files together in a single download link.

You may have files on your PHP server, of any type (image, documents, code, etc.), and you may want to zip these files in a GZip archive automatically with your PHP script.

You can create a gzip file with something like this...

$filep = gzopen("../data/MyZipFileName.gz", 'w9');

Then you write whatever text you want to it with something like this...

gzwrite($filep, $text);

When you are finished, you let the PHP server know you're done by adding this to the end of your script...

gzclose($filep);

If you want to download this as a file, you need to send file headers, so that you download the gzip file at the PHP URL, instead of just looking at the gzip file contents through the browser (which would be a garbled mess, as it is a compressed archive).

You can do that with this...

header("Content-disposition: attachment;filename=MyArchiveFile.gz");
readfile("../data/MyZipFileName.gz");

No comments:

Post a Comment