How to unzip a file in PHP

1869 views 1 year ago PHP

If you are working in a project which contains lots of file, then probably there is a feature of file zipping and unzipping. With this feature, user can upload and download multiple files using zip.

To handle zip files, php has in-built ZipArchive class. With this class you can create zip files or unzip. In this article, we will share you how you can unzip file and get all internal files details.

ZipArchive class has static extractTo() method which extract zip files to desired location. extractTo() method accepts two parameters: First one is destination path of zip file and second is a single file name which will be extracted or you can use it to pass an array of files.

Example:

<?php
$zip = new ZipArchive;
$res = $zip->open('data.zip');
if ($res === true) {
    $zip->extractTo('/uploads/images/');
    $zip->close();
    echo('extract completed.');
} else {
    echo('extract couldn\'t completed.');
}

Now suppose you only want to extract files from zip file. Then pass second parameter with array of file names.

Here is the example of that:

<?php
$zip = new ZipArchive;
$res = $zip->open('data.zip');
if ($res === true) {
    $zip->extractTo('/uploads/images/', ['first.jpg', 'second.jpg', 'forth.jpg']); // we don't need third.jpg file to extract
    $zip->close();
    echo('extract completed.');
} else {
    echo('extract couldn\'t completed.');
}

I hope you liked the article.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]