Extract ZIP File using PHP

The archive files are used for data compression. The ZIP, Gzip, and RAR are the commonly used file format to archive files. Generally, we use computer software to extract archive files (ZIP, Gzip, RAR, etc.). But, the archive file also can be extracted on the fly using PHP. You can easily create ZIP file dynamically and extract ZIP file from the script with PHP.

The ZipArchive class provides an easy way to extract the archive contents in PHP. You can extract the ZIP file on the server using ZipArchive in PHP. In this tutorial, we will show you how to extract the ZIP file in PHP. Not only the ZIP file but also the other archive files (GZIP and RAR) can be extracted in PHP using our example code snippets.

To make the archive extraction process simple, we have grouped all the code in a PHP class and created a custom library named Extractor. This library provides an instant and structured way to implement file extract functionality in PHP.

Extractor Class

The Extractor class helps to extract archive files (zip/gzip/rar) on the server using PHP ZipArchive.

  • extract() – This function checks the extension of the given file and calls the suitable extractor function.
    • $archive – Relative path of the archive file to be extracted.
    • $destination – The location where to extract files.
  • extractZipArchive() – It is a helper function of Extractor class. This function decompress or extract a ZIP archive file (.zip) using ZipArchive in PHP.
  • extractGzipFile() – It is a helper function of Extractor class. This function decompress or extract a Gzip archive file (.gz) using gzread() in PHP.
  • extractRarArchive() – It is a helper function of Extractor class. This function decompress or extract a RAR archive file (.rar) using RarArchive in PHP.
<?php
/**
 * Class Extractor
 *
 * Extract a archive (zip/gzip/rar) file.
 * 
 * @author CodexWorld
 * @url https://www.codexworld.com
 * 
 */
class Extractor {

    
/**
     * Checks file extension and calls suitable extractor functions.
     *
     * @param $archive
     * @param $destination
     */
    
public static function extract($archive$destination){
        
$ext pathinfo($archivePATHINFO_EXTENSION);
        switch (
$ext){
            case 
'zip':
                
$res self::extractZipArchive($archive$destination);
                break;
            case 
'gz':
                
$res self::extractGzipFile($archive$destination);
                break;
            case 
'rar':
                
$res self::extractRarArchive($archive$destination);
                break;
        }
        return 
$res;
    }
    
    
/**
     * Decompress/extract a zip archive using ZipArchive.
     *
     * @param $archive
     * @param $destination
     */
    
public static function extractZipArchive($archive$destination){
        
// Check if webserver supports unzipping.
        
if(!class_exists('ZipArchive')){
            
$GLOBALS['status'] = array('error' => 'Your PHP version does not support unzip functionality.');
            return 
false;
        }
    
        
$zip = new ZipArchive;
    
        
// Check if archive is readable.
        
if($zip->open($archive) === TRUE){
            
// Check if destination is writable
            
if(is_writeable($destination '/')){
                
$zip->extractTo($destination);
                
$zip->close();
                
$GLOBALS['status'] = array('success' => 'Files unzipped successfully');
                return 
true;
            }else{
                
$GLOBALS['status'] = array('error' => 'Directory not writeable by webserver.');
                return 
false;
            }
        }else{
            
$GLOBALS['status'] = array('error' => 'Cannot read .zip archive.');
            return 
false;
        }
    }
    
    
/**
     * Decompress a .gz File.
     *
     * @param $archive
     * @param $destination
     */
    
public static function extractGzipFile($archive$destination){
        
// Check if zlib is enabled
        
if(!function_exists('gzopen')){
            
$GLOBALS['status'] = array('error' => 'Error: Your PHP has no zlib support enabled.');
            return 
false;
        }
    
        
$filename pathinfo($archivePATHINFO_FILENAME);
        
$gzipped gzopen($archive"rb");
        
$file fopen($filename"w");
    
        while (
$string gzread($gzipped4096)) {
            
fwrite($file$stringstrlen($string));
        }
        
gzclose($gzipped);
        
fclose($file);
    
        
// Check if file was extracted.
        
if(file_exists($destination.'/'.$filename)){
            
$GLOBALS['status'] = array('success' => 'File unzipped successfully.');
            return 
true;
        }else{
            
$GLOBALS['status'] = array('error' => 'Error unzipping file.');
            return 
false;
        }
    }
    
    
/**
     * Decompress/extract a Rar archive using RarArchive.
     *
     * @param $archive
     * @param $destination
     */
    
public static function extractRarArchive($archive$destination){
        
// Check if webserver supports unzipping.
        
if(!class_exists('RarArchive')){
            
$GLOBALS['status'] = array('error' => 'Your PHP version does not support .rar archive functionality.');
            return 
false;
        }
        
// Check if archive is readable.
        
if($rar RarArchive::open($archive)){
            
// Check if destination is writable
            
if (is_writeable($destination '/')) {
                
$entries $rar->getEntries();
                foreach (
$entries as $entry) {
                    
$entry->extract($destination);
                }
                
$rar->close();
                
$GLOBALS['status'] = array('success' => 'File extracted successfully.');
                return 
true;
            }else{
                
$GLOBALS['status'] = array('error' => 'Directory not writeable by webserver.');
                return 
false;
            }
        }else{
            
$GLOBALS['status'] = array('error' => 'Cannot read .rar archive.');
            return 
false;
        }
    }
    
}

Extract ZIP in PHP

Use Extractor class to extract archive files (ZIP, GZIP, and RAR) to the specified destination using PHP.

  • Include and initialize the Extractor class.
  • Specify the path of the archive file (ZIP / Gzip / RAR) which you want to extract.
  • Specify the destination to extract the ZIP file on the server.
  • Call the extract() function of Extractor class.
// Include and initialize Extractor class
require_once 'Extractor.class.php';
$extractor = new Extractor;

// Path of archive file
$archivePath '/path/to/archive.zip';

// Destination path
$destPath '/destination/dir/';

// Extract archive file
$extract $extractor->extract($archivePath$destPath);

if(
$extract){
    echo 
$GLOBALS['status']['success'];
}else{
    echo 
$GLOBALS['status']['error'];
}

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

Leave a reply

keyboard_double_arrow_up