PHP compression Stream Wrappers


Introduction

In PHP, zlib://, bzip2:// and zip:// represent wrappers for respective compression streams.

compress:zlib://

This works similar to gzopen() function, however, it can be used with filesystem functions like fread() and others.

compress://bzip2

This is similar to bzopen() function. Both stream wrappers operate even on systems not capable of supporting fopencookie.

zip://

The ZIP extension registers this wrapper. From PHP 7.2.0 onwards, archives encrypted with passwords are supported. It is possible to set password with password context option.

Examples

zlib compression can be applied with following PHP code

<?php
file_put_contents("compress.zlib://test.txt.gz","Hello World\r
"); ?>

To uncompress, we can use following syntax

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

We can also use built-in copy() function to build compressed zlib file and uncompress the same

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

Updated on: 22-Sep-2020

313 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements