4

How would I turn a directory into a zip file with PHP?

Thanks.

Alix Axel
  • 151,645
  • 95
  • 393
  • 500
usertest
  • 27,132
  • 30
  • 72
  • 94

3 Answers3

12

From "Zip a directory in PHP".


Here is a simple function that can compress any file or directory recursively, only needs the zip extension to be loaded.

function Zip($source, $destination)
{
    if (extension_loaded('zip') === true)
    {
        if (file_exists($source) === true)
        {
            $zip = new ZipArchive();

            if ($zip->open($destination, ZIPARCHIVE::CREATE) === true)
            {
                $source = realpath($source);

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

                    foreach ($files as $file)
                    {
                        $file = realpath($file);

                        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();
        }
    }

    return false;
}

Call it like this:

Zip('/folder/to/compress/', './compressed.zip');

EDIT - This one won't keep the folder structure (check my comment):

function Zip($source, $destination)
{
    if (extension_loaded('zip') === true)
    {
        if (file_exists($source) === true)
        {
            $zip = new ZipArchive();

            if ($zip->open($destination, ZIPARCHIVE::CREATE) === true)
            {
                if (is_dir($source) === true)
                {
                    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

                    foreach ($files as $file)
                    {
                        if (is_file($file) === true)
                        {
                            $zip->addFromString(basename($file), file_get_contents($file));
                        }
                    }
                }

                else if (is_file($source) === true)
                {
                    $zip->addFromString(basename($source), file_get_contents($source));
                }
            }

            return $zip->close();
        }
    }

    return false;
}
Community
  • 1
  • 1
Alix Axel
  • 151,645
  • 95
  • 393
  • 500
  • This keeps the directory structure. Is there a way for it not to keep the structure? So all the files are in one folder. – usertest Jan 22 '10 at 21:27
  • @unknown (google): Not reliably, since a file can overwrite an already zipped file. – Alix Axel Jan 22 '10 at 21:29
  • @unknown (google): I've updated the function to what you seem to want. – Alix Axel Jan 22 '10 at 21:43
  • if anyone includes larger zip files (or other), I would suggest changing: $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file)); --- to --- $zip->addFile($file, $file); --- otherwise this function silently fails. jp[] – Jeffz May 31 '11 at 21:38
  • @Jeffz: Using the `addFile()` method also has its quirks, see http://bugs.php.net/bug.php?id=40494 and http://pecl.php.net/bugs/bug.php?id=9443. – Alix Axel Jun 01 '11 at 01:22
0

This one seems to be shorter shorter.

<?php

$sourcePath = realpath('../../');

$archiv = new ZipArchive();
$archiv->open('archiv.zip', ZipArchive::CREATE);
$dirIter = new RecursiveDirectoryIterator($sourcePath);
$iter = new RecursiveIteratorIterator($dirIter);

foreach($iter as $element) {
    /* @var $element SplFileInfo */
    $dir = str_replace($sourcePath, '', $element->getPath()) . '/';
    if ($element->isDir()) {
        $archiv->addEmptyDir($dir);
    } elseif ($element->isFile()) {
        $file         = $element->getPath() .
                        '/' . $element->getFilename();
        $fileInArchiv = $dir . $element->getFilename();
        // add file to archive 
        $archiv->addFile($file, $fileInArchiv);
    }
}

// Save a comment
$archiv->setArchiveComment('Backup ' . $absolutePath);
// save and close 
$archiv->close();

// to extract

$destinationPath = realpath('tmp/');
$archiv = new ZipArchive();
$archiv->open('archiv.zip');
$archiv->extractTo($destinationPath);
streetparade
  • 32,000
  • 37
  • 101
  • 123
0

For windows servers you need to alter it or you get the whole directory hierarchy from C:

    foreach ($files as $file)
    {
        $currentfile = substr($file, strpos($file, "\\") + 1);
        $file = str_replace('\\', '/', $file);

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

        $file = realpath($file);

        if (is_dir($file) === true)
        {
            $dirloc = $currentfile;
            $zip->addEmptyDir($dirloc); 
        }
        elseif(is_file($file) === true)
        {
            $fileloc = $currentfile;
            $zip->addFromString($fileloc,file_get_contents($file)); 
       }
    } 
Robert Pounder
  • 1,490
  • 1
  • 14
  • 29