Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.
Hi all, please see this major site announcement: https://www.boards.ie/discussion/2058427594/boards-ie-2026

PHP - Zip A Directory

  • 07-09-2011 12:47PM
    #1
    Registered Users, Registered Users 2 Posts: 7,994 ✭✭✭


    Hi Folks,

    I'm looking for a way to ZIP an entire directory using PHP. I won't know whats in the directory before I ZIP it.

    Here's my code so far but I get a empty folder when downloaded.

    Any help appreciated!
    $archive_name = "archive.zip"; // name of zip file
    $archive_folder = "uploads"; // the folder I want to archive
    
    $zip = new ZipArchive;
    if ($zip -> open($archive_name, ZipArchive::CREATE) === TRUE)
    {
        $dir = preg_replace('/[\/]{2,}/', '/', $archive_folder."/");
       
        $dirs = array($dir);
        while (count($dirs))
        {
            $dir = current($dirs);
            $zip -> addEmptyDir($dir);
           
            $dh = opendir($dir);
            while($file = readdir($dh))
            {
                if ($file != '.' && $file != '..')
                {
                    if (is_file($file))
                        $zip -> addFile($dir.$file, $dir.$file);
                    elseif (is_dir($file))
                        $dirs[] = $dir.$file."/";
                }
            }
            closedir($dh);
            array_shift($dirs);
        }
       
        $zip -> close();
        echo 'Archive Done!';
    }
    else
    {
        echo 'Error, can\'t create a zip file!';
    }
    


Comments

Advertisement
Advertisement