Extraer un fichero ZIP con PHP

ZIP es uno de los formatos de archivo más utilizados para comprimir datos. Por lo general solemos utilizar algún software para extraer el contenido de este tipo de archivos (ZIP, Gzip, RAR...) Pero en esta ocasión te mostraremos cómo hacerlo mediante un script de PHP sobre la marcha.

La clase ZipArchive, de la que te hablamos en otro artículo, nos proporcionará una manera sencilla de extraer el contenido de ficheros comprimidos con PHP. Ojo, no solo extraeremos ficheros ZIP, mediante este tutorial podrás extraer en tu proyecto web otro tipo de ficheros como por ejemplo Gzip o también RAR. Una vez dicho todo esto, vamos a ver cómo extraer ficheros ZIP con PHP.

 

Clase Extractor

La clase Extractor nos ayudará a extraer el contenido de un fichero comprimido (zip/gzip/rar) en el servidor utilizando ZipArchive.

  • extract() - Esta función comprueba la extensión de un fichero dado y llama a su correspondiente función para extraer el contenido según el formato

  • extractZipArchive() - Esta función descomprime o extrae el contenido de un fichero ZIP (.zip)
  • extractGzipArchive() - Esta función descomprime o extrae el contenido de un fichero Gzip (.gz)
  • extractRarArchive() - Esta función descomprime o extrae el contenido de un fichero RAR (.rar)
<?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($archive, PATHINFO_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($archive, PATHINFO_FILENAME);
        $gzipped = gzopen($archive, "rb");

        $file = fopen($filename, "w");
    
        while ($string = gzread($gzipped, 4096)) {
            fwrite($file, $string, strlen($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;
        }
    }
    
}

Extraer ZIP en PHP

La clase Extractor descomprime ficheros comprimidos (ZIP, GZIP y RAR) a un destino específico mediante PHP.

Aquí tienes cómo utilizar la clase:

// 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'];
}

COMPARTE ESTE ARTÍCULO

COMPARTIR EN FACEBOOK
COMPARTIR EN TWITTER
COMPARTIR EN LINKEDIN
COMPARTIR EN WHATSAPP
ARTÍCULO ANTERIOR