Unzip a Zip File Using PHP

In Previous articles, we have learnt few operations on ZIP files using PHP and JavaScript. Most of the articles were about creating Zip files In this article, we will see how to unzip a ZIP archive using PHP.
For unzipping an archive, we will use unzip command of unix or linux server. See the sample code below.
Also Read:
- Create and Download ZIP file with PHP
- Create ZIP files using JavaScript
- Backup a Folder to a ZIP file
Add this code in functions.php file.
<?php function unzip($sourcelocation,$newLocation){ if(exec("unzip $sourcelocation",$arr)){ mkdir($newLocation); for($i = 1;$i< count($arr);$i++){ $file = trim(preg_replace("~inflating: ~","",$arr[$i])); copy($sourcelocation.'/'.$file,$newLocation.'/'.$file); unlink($sourcelocation.'/'.$file); } return true; }else{ return false; } } ?>
Now use this functions.php file whenever you want to use unzip function.
<?php include 'functions.php'; if(unzip('zipfolder/test.zip','unziped/unpackedZip')) echo 'Success!'; else echo 'Error'; ?>
If you have any confusion, you can ask us via comments.
Leave a comment
Comment policy: We love comments and appreciate the time that readers spend to share ideas and give feedback. However, all comments are manually moderated and those deemed to be spam or solely promotional will be deleted.