How can I extract or uncompress gzip file using php?

In PHP, you can extract or uncompress gzip files using built-in functions like gzopen(), gzread(), and gzeof(). This allows you to decompress .gz files programmatically.

Using gzread() Function

The most common approach is to read the gzipped file in chunks and write the uncompressed data to a new file ?

<?php
$file_name = 'data.dump.gz';
$buffer_size = 4096; // The number of bytes to read at a time (4KB)
$out_file_name = str_replace('.gz', '', $file_name);

// Open the gzipped file in read binary mode
$file = gzopen($file_name, 'rb');
// Create the output file in write binary mode
$out_file = fopen($out_file_name, 'wb');

// Read and extract until end of file
while (!gzeof($file)) {
    fwrite($out_file, gzread($file, $buffer_size));
}

// Close both files
fclose($out_file);
gzclose($file);

echo "File extracted successfully to: " . $out_file_name;
?>
File extracted successfully to: data.dump

Using gzfile() Function

For smaller files, you can read the entire compressed content into an array ?

<?php
$file_name = 'sample.txt.gz';
$lines = gzfile($file_name);

// Write all lines to uncompressed file
$out_file = fopen('sample.txt', 'w');
foreach ($lines as $line) {
    fwrite($out_file, $line);
}
fclose($out_file);

echo "Total lines extracted: " . count($lines);
?>
Total lines extracted: 150

Key Points

  • Buffer Size: Use 4096 bytes (4KB) for optimal performance when reading large files
  • File Modes: Use 'rb' for reading gzipped files and 'wb' for writing binary output
  • Memory Usage: gzread() is memory-efficient for large files, while gzfile() loads everything into memory
  • Error Handling: Always check if gzopen() returns false before proceeding

Conclusion

Use gzread() with a buffer for large files and gzfile() for smaller text files. Always close file handles properly to free system resources after extraction.

Updated on: 2026-03-15T08:50:19+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements