PHP How to zip a folder

For ziping and unziping we can use PHP ZipArchive libraries

bellow code will zip a folder recursively

<?php
// Get real path for our folder
echo $rootPath = realpath('Newfolder');

// Initialize archive object
$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE );

// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($rootPath), RecursiveIteratorIterator::LEAVES_ONLY);

foreach ($files as $name => $file)
{
    // Skip directories (they would be added automatically)
    if (!$file->isDir())
    {
        // Get real and relative path for current file
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);

        // Add current file to archive
        $zip->addFile($filePath, $relativePath);
    }
}

// Zip archive will be created only after closing object
$zip->close();
?>

 

For unzip

<?php    
    $zip = new ZipArchive;
    $zip->open('sample.zip');
    $zip->extractTo('./');
    $zip->close(); 
?>

Requirements :

http://php.net/manual/en/zip.requirements.php

Note : – php5.6 bellow version wi;; not support to create password protected zip,  php5.6 and above will support to create password protected archives. All you need is to add this code ZipArchive::setPassword($password).

ref:

http://php.net/manual/en/book.zip.php, http://php.net/manual/en/zip.examples.php, http://stackoverflow.com/questions/4914750/how-to-zip-a-whole-folder-using-php

Author: bm on May 12, 2016
Category: php