2

i am having troubles with create a zip archive file.

I have a folder 2016_03_01_full, which should be archived available by this path.

C:\OpenServer\domains\project\backup\2016_03_01_full

Zip Archive should be created with same name as folder 2016_03_01_full.zip in

C:\OpenServer\domains\stereoshoots\backup\2016_03_01_full.zip

This is my function

public function createArchive($source, $destination) {
        $zip = new \ZipArchive();

        if(!$zip->open($destination, \ZipArchive::CREATE))
            return false;

        $source = str_replace('\\', '/', realpath($source));

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

            foreach ($files as $file) {
                $file = str_replace('\\', '/', $file);

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

                $file = realpath($file);

                if(is_dir($file) === true)
                    $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
                elseif(is_file($file) === true)
                    $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
            }
        }
        elseif(is_file($source) === true)
            $zip->addFromString(basename($source), file_get_contents($source));

        return $zip->close();
    }

$this->createArchive($this->getBackupFolderDir().'/', $this->getBackupFolderDir().'.zip');

It does create archive but it created all folders from path. So when i open zip i see OpenServer\domains\project\backup\2016_03_01_full folders in it. Is there a way to archive without path folders?

thanks!

Tigran
  • 633
  • 4
  • 17
  • 26

1 Answers1

0

The "destination path" for the created archive contains the absolute(full) path to the intended file.
To omit full path - specify only filename as destination path(extracting filename with substr and strrpos functions):

...
$destination = substr($destination, strrpos($destination, DIRECTORY_SEPARATOR) + 1);
if (!$zip->open($destination, \ZipArchive::CREATE)) return false;
...
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105