Showing posts with label gzip. Show all posts
Showing posts with label gzip. Show all posts

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");

Tuesday, August 28, 2018

Downloading and Unzipping GZip on Your PHP Server From Another Web Server

Some site may offer a gzip file that you want to run with your PHP script, but that gzip file is always being updated and you want your script to download the newest version and use its contents.

This can be done very easily.

First, download the file you want to unzip, using something like this...

$file = file_put_contents("../data/SomeZipFileLocation.gz", fopen("SomeURL", 'r'), LOCK_EX);

Then you can read the contents like this...

$file = gzopen("../data/SomeZipFileLocation.gz", 'rb');
while (!gzeof($file)) {
print(gzread($file, 4000));
}

This will loop through each of the 4,000 bytes in the file from the gzip and display them.

Using this technique, you won't ever have to manually download and unzip these gzipped files to use the newest version with your code.