PHP How to zip a folder

For ziping and unziping we can use PHP ZipArchive libraries

bellow code will zip a folder recursively

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

// Initialize archive object
$zip = new ZipArchive();
$zip->open('', 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


For unzip

    $zip = new ZipArchive;

Requirements :

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).


Author: bm on May 12, 2016
Category: php

Your comment:

Your Name


Last articles