Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

PHP - Zip A Directory

Options
  • 07-09-2011 12:47pm
    #1
    Registered Users Posts: 8,004 ✭✭✭


    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