-1

Hi Guys i want to zip my project folder so this i can backup it , i used this script which i found in GitHub :

function Zip($source, $destination)
{
    $Exclude = ['assets','vendor','cache'];
    if (is_string($source)) $source_arr = array($source);

    if (!extension_loaded('zip')) {
        return false;
    }

    $zip = new ZipArchive();
    if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
        return false;
    }

    foreach ($source_arr as $source)
    {
        if (!file_exists($source)) continue;
        $source = str_replace('\\', '/', realpath($source));

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

            foreach ($files as $file)
            {
                if (!in_array($file, $Exclude)) {
                    $file = str_replace('\\', '/', 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();
}  

The function working perfectly the only problem is it zips all the subfolder in my project when i don't want it to zip the assets & vendor folders . Thanks fellow Developers .

Noufair Younes
  • 649
  • 1
  • 5
  • 11
  • 1
    Does this answer your question? [How to zip a whole folder using PHP](https://stackoverflow.com/questions/4914750/how-to-zip-a-whole-folder-using-php) – Jaquarh Jan 18 '22 at 17:06
  • No sir , it just shows how to zip not how to exclude some subfolders . – Noufair Younes Jan 18 '22 at 17:14
  • Pretty sure there is an answer that states `If you have subfolders and you want to preserve the structure of the folder do this:` no? – Jaquarh Jan 19 '22 at 01:44

1 Answers1

0

At the beginning of the function you can define those paths in an $exclude array. Then, in your foreach($source_arr as $source) loop, check if realpath($source) is found in that $exclude array. If it is, continue, skipping the folder.

This solution isn't very portable though. If you're wanting to backup, I suggest using Github & create a private repository. You can then easily setup a .gitignore file that will prevent those directories you mentioned from being committed.

Quasipickle
  • 4,383
  • 1
  • 31
  • 53