Unzip your zip archive using PHP

prerequisites:

  • (PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)
  • Make sure zip extension is enabled

Here is the sample code to unzip a particular zip archive file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
// DISPLAY ERROR IN DEVELOPMENT MODE
// FOR PRODUCTION MODE ITS NOT RECOMMENDED
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// CURRENT DIRECTORY OR YOUR PROJECT DIRECTORY
define('_PATH', dirname(__FILE__));

// EXTRACT PATH WHERE YOU ZIP FILE WILL BE UNZIPPED
$zip_extract_directory = _PATH.'/extract_dir';

// ZIP FILE NAME
$zip_file_name = './myzip.zip';
$zip = new ZipArchive;
$response = $zip->open($zip_file_name);
if ($response === TRUE) {
echo 'SUCCESSFULLY UNZIPPED';
$zip->extractTo($zip_extract_directory);
$zip->close();
} else {
echo 'UNABLE TO EXTRACT YOUR ZIP FILE , ERROR CODE :'.$response;
}