How do you create a .gz file using PHP?

How do you create a .gz file using PHP?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

How do you create a .gz file using PHP?

Creating a compressed archive is a common requirement for reducing storage costs or speeding up data transfers, but the approach in PHP depends heavily on whether you are dealing with text-based archives or binary files. The most straightforward path for text content involves the GZip compression method, while binary data often requires ZipArchive or specific memory handling to avoid corruption.

For pure text files, such as log entries or configuration scripts, the GZip extension provides a direct solution. You instantiate a GZFile object pointing to your source file and then use the compress() method to generate the output. This approach writes the compressed stream directly to disk if you provide an output path, or to a variable string if you omit it.

$gz = new GZip('/path/to/input.txt', '/path/to/output.gz');
$gz->compress();

The underlying library handles the necessary headers automatically. However, this method is strictly for text streams. If you attempt to use GZFile on binary data like images or executables without special care, the resulting file may be unreadable by standard tools because the compression algorithm expects ASCII-compatible input. For general-purpose archiving that supports both text and binary files with integrity checks, the ZipArchive class is the preferred native PHP solution.

$zip = new ZipArchive();
if ($zip->open('/path/to/output.zip', ZipArchive::CREATE) === true) {
    $zip->addFile('/path/to/input.bin', 'input.bin');
    $zip->close();
}

While this creates a .zip file, many systems expect .gz specifically for single-file compression. To achieve the exact .gz format with binary safety using standard PHP functions, you should leverage the shell command line via exec(), system(), or popen(). This delegates the actual compression work to the system's gzip utility, which is highly optimized and handles edge cases better than a pure PHP implementation.

$source = '/path/to/input.bin';
$output = $source . '.gz';

exec("gzip -c '{$source}' > '{$output}'", $output_lines, $return_var);

if ($return_var === 0) {
    // Compression successful
} else {
    // Handle error
}

This command line approach is robust because the gzip utility manages memory streams correctly. The -c flag tells gzip to read from standard input and write to standard output, allowing redirection via shell operators without altering the original file until the operation completes. This is critical for production environments where data integrity is paramount; you avoid partial writes or race conditions that might occur if trying to buffer large files entirely in PHP memory before writing.

If your environment lacks the gzip binary or you need a pure PHP solution for text-only scenarios, the GZip class remains viable but requires strict adherence to text-based inputs. Always verify the return codes from external commands before assuming success.

For projects built on the Laravel framework, there are packages that abstract these details further, but understanding the underlying mechanism ensures you can troubleshoot issues when external dependencies fail. If you find yourself needing complex streaming logic or specific compression levels beyond standard defaults, wrapping the shell command in a process manager or using the Symfony Process component offers better control over timeouts and resource limits compared to raw PHP streams.

Ultimately, the choice between a native PHP class and a shell wrapper depends on your data type and performance requirements. Text files benefit from the speed of GZip, while binary archives demand the reliability of the system gzip tool or a dedicated ZIP library.

Our network