d
Amit DhamuSoftware Engineer
 

ZipArchive in PHP

3 minute read 00000 views

You will need to ensure the zip extension is enabled in your php.ini file.

$zip = new ZipArchive();
$result = $zip->open('file.zip', ZipArchive::CREATE);

if ($result) {
    // 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 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)) {
        $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 . '/'));
            } elseif (is_file($file)) {
                $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
            }
        }
    } elseif (is_file($source)) {
        $zip->addFromString(basename($source), file_get_contents($source));
    }
    return $zip->close();
}

$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