0

Short explanation:

There are some files in the directory

Yii::app()->runtimePath.'/temp/myDir/';

These files should be zipped in the same directory like:

Yii::app()->runtimePath.'/temp/myDir/files.zip

Following construction gives no errors, but zip-file is not created.

$zip = new ZipArchive();
$path = Yii::app()->runtimePath.'/temp/myDir/';

// Open an empty ZIP-File to write into
$ret = $zip->open('files.zip', ZipArchive::OVERWRITE);

if ($ret !== TRUE) {
    printf('Failed with code %d', $ret);
} else {
    $options = array('add_path' => $path, 'remove_all_path' => TRUE);
    $zip->addGlob('*.{png,gif,jpg,pdf}', GLOB_BRACE, $options);
    $res = $zip->close();
}

What is my mistake? Directory name is correct and it is writable (CHMOD 777).

NDM
  • 6,731
  • 3
  • 39
  • 52

3 Answers3

2

this works (excerpt):

$ret = $zip->open($path.'files.zip', ZipArchive::OVERWRITE);
...
$options = array('remove_all_path' => TRUE);
$zip->addGlob($path.'*.{png,gif,jpg,pdf}', GLOB_BRACE, $options);
  • 3
    but I'cant get the directory structure removed in the created Zip-File, can someone help me why? –  Nov 15 '13 at 13:20
  • @user2227400: If you don't pass `add_path` in `$options` array, `remove_all_path` will not take any effect, besides if you pass `'add_path' => ''`, `addGlob` will return `false`. – samluthebrave Dec 07 '16 at 03:47
  • how do I set the compression level using `addGlob()`? – Paranoid Android Feb 16 '18 at 16:24
0

Reusing the code from Alireza Fallah in (How to zip a whole folder using PHP) appling basename to the iteration of files, you´ll have zip without path structure :)

function create_zip($files = array(), $dest = '', $overwrite = false) {
    if (file_exists($dest) && !$overwrite) {
        return false;
    }
    if (($files)) {
        $zip = new ZipArchive();
        if ($zip->open($dest, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
            return false;
        }
        foreach ($files as $file) {
            $zip->addFile($file, basename($file));
        }
        $zip->close();
        return file_exists($dest);
    } else {
        return false;
    }
}

function addzip($source, $destination) {
    $files_to_zip = glob($source . '/*');
    create_zip($files_to_zip, $destination);
    echo "done";
}
Community
  • 1
  • 1
0

The problem is most likely to be the wrong $flag argument passed to method ZipArchive::open ( string $filename [, int $flags ] ). In your case, it should be $ret = $zip->open('files.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);

If zip-file does not already exist, $ret = $zip->open('files.zip', ZipArchive::OVERWRITE); var_dump($ret); would print int(11), which is the equivalent value of constant ZipArchive::ER_OPEN, whose description is Can't open file..

samluthebrave
  • 163
  • 1
  • 7