Amit Dhamu

Writes Code

ZipArchive in PHP

You will need to ensure the extension=php_zip.dll is enabled in your php.ini file.

<?php
   $zip = new ZipArchive();
   $result = $zip->open("file.zip", ZipArchive::CREATE);

   if($result === TRUE) {
      // Zip Creation Successful
      $zip->addFile("filepath", "filename");
      $zip->close();
   } else {
      // Failed Creating Zip
   }

   // Optional - To force download straight away
   header("Content-Type: application/zip");
   header("Content-Length: " . filesize("file.zip"));
   header("Content-Disposition: attachment; filename=file.zip");
   readfile("file.zip");
   unlink("file.zip");
?>


Alternative Method

// Function
function Zip($source, $destination) {
    if(!extension_loaded('zip') || !file_exists($source)) {
        return false;
    }

    $zip = new ZipArchive();

    if(!$zip->open($destination, ZIPARCHIVE::CREATE)) {
        return false;
    }

    if(is_dir($source) === true) {
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source));

        foreach($files as $file) {
            $file = str_replace('', '/', $file);

            if(in_array(substr($file, strrpos($file, '/')+1), array('download.php')))
              continue;

            if(in_array(substr($file, strrpos($file, '/')+1), array('.', '..')))
                continue;

            if(is_dir($file) === true) {
                $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
            } else if (is_file($file) === true) {
                $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
            }
        }
    } else if(is_file($source) === true) {
        $zip->addFromString(basename($source), file_get_contents($source));
    }
    return $zip->close();
}

// Usage
$directory = "/folder/to/zip/";
$zip_name = "files.zip";

if(Zip($directory, $zip_name)) {
    header("Content-Type: application/zip");
    header("Content-Length: " . filesize($zip_name));
    header("Content-Disposition: attachment; filename=".$zip_name."");
    readfile($zip_name);
    unlink($zip_name);
}


Credits for Alternative Method


ziparchive / zip / php

← Full Table Structure Email Using PHPMailer →