How do you create a .gz file using PHP?

AlBeebe picture AlBeebe · May 20, 2011 · Viewed 53.1k times · Source

I would like to gzip compress a file on my server using PHP. Does anyone have an example that would input a file and output a compressed file?

Answer

AlBeebe picture AlBeebe · May 20, 2011

This code does the trick

// Name of the file we're compressing
$file = "test.txt";

// Name of the gz file we're creating
$gzfile = "test.gz";

// Open the gz file (w9 is the highest compression)
$fp = gzopen ($gzfile, 'w9');

// Compress the file
gzwrite ($fp, file_get_contents($file));

// Close the gz file and we're done
gzclose($fp);