PHP compression Stream Wrappers

In PHP, compression stream wrappers provide an efficient way to handle compressed files directly through filesystem functions. The main compression wrappers are compress.zlib://, compress.bzip2://, and zip://.

compress.zlib:// Wrapper

This wrapper works similar to the gzopen() function but can be used with standard filesystem functions like fread(), file_get_contents(), and file_put_contents().

Creating Compressed Files

You can create gzip−compressed files directly using the zlib wrapper −

<?php
file_put_contents("compress.zlib://test.txt.gz", "Hello World\r<br>");
echo "File compressed successfully!";
?>

Reading Compressed Files

To read and decompress the content, use the same wrapper −

<?php
echo file_get_contents("compress.zlib://test.txt.gz");
?>

Using copy() Function

The built−in copy() function can also work with compression wrappers to compress and decompress files −

<?php
// Create a sample file
file_put_contents('file.txt', 'Sample content for compression');

// Compress the file
copy('file.txt', 'compress.zlib://file.txt.gz');

// Decompress the file
copy('compress.zlib://file.txt.gz', 'decompressed_file.txt');

echo "Compression and decompression completed!";
?>

compress.bzip2:// Wrapper

This wrapper is similar to the bzopen() function and works with bzip2 compression format −

<?php
// Compress using bzip2
file_put_contents("compress.bzip2://data.bz2", "Data to compress with bzip2");

// Read compressed bzip2 file
echo file_get_contents("compress.bzip2://data.bz2");
?>

zip:// Wrapper

The ZIP extension registers this wrapper. From PHP 7.2.0 onwards, password−protected archives are supported using the password context option −

<?php
// Reading a file from ZIP archive
$content = file_get_contents("zip://archive.zip#file.txt");

// For password-protected ZIP (PHP 7.2+)
$context = stream_context_create([
    'zip' => ['password' => 'your_password']
]);
$content = file_get_contents("zip://protected.zip#file.txt", false, $context);
?>

Key Benefits

Both zlib and bzip2 stream wrappers operate on systems that don't support fopencookie, making them widely compatible. These wrappers integrate seamlessly with PHP's filesystem functions.

Conclusion

PHP compression stream wrappers provide a convenient way to handle compressed files using standard filesystem functions. They offer seamless integration and wide compatibility across different systems.

Updated on: 2026-03-15T09:27:59+05:30

542 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements