PHP: How to Extract a ZIP Archive?

approximately 2 minutes of reading

Extracting a ZIP archive in PHP is a very easy process. All you have to know is the location to a ZIP archive you are about to extract. Follow this brief tutorial to find out how the process looks like.

Before we begin, familiarize yourself with the official documentation for the ZipArchive class. Next (if you use Composer) ensure that particular extension is required.

composer require ext-zip
Object Instantiation

This is the most obvious step, instantiate it via:

$zip = new ZipArchive;

Now we should know where the ZIP we're about to extract is located as well as where exactly we want to extract it.

Dummy Archive

My dummy ZIP file is a compressed folder that contains 3 empty text files, created via touch command.

Archive Location and Destination

Let's pick Laravel's storage path as an example, but really this article can be fully framework-agnostic, so you should be able to provide location without any additional helpers.

In my case in the root of my Laravel project I have created a tmp directory and moved the archive.zip there. For the destination, in the same tmp directory I have created nested one called my-docs, where I would like to see my 3 text files being extacted.

$absolutePathToZip = storage_path('tmp') . '/' . 'archive.zip';
$absolutePathToDestination = storage_path('tmp') . '/my-docs';

Dumping this inside the container, gives:

"/var/www/storage/tmp/archive.zip"
"/var/www/storage/tmp/my-docs"
Opening and Extraction

Open the archive by calling open() method and provide a path to the compressed file:

$zip->open($absolutePathToZip);

It is a good habit here to ensure that the file was opened correctly and in case it didn't, act accordingly. Assign the result of calling open() into variable and if it's not true, then throw an \Exception.

$result = $zip->open($absolutePathToZip);

if (!$result) {
    throw new Exception('Unable to open given ZIP file');
}

Next, let's call extractTo() and provide a path to the destination location:

$zip->extractTo($absolutePathToDestination);

Finally, don't forget to close the handle:

$zip->close();

With this, your files should be correctly extracted.

[email protected]:/var/www/storage/tmp/my-docs# ls
file1.txt  file2.txt  file3.txt

This is it. Now you know how to extract a ZIP archive using PHP.


Words: 374
Published in: PHP