2

I'm trying to figure out this problem but I cannot imagine why it keeps happening. I'm adding files to a ZipArchive and when I try to close it, it get the error that the destination is a directory. But I'm pretty sure it is not.

This is the code of the zip function:

function create_zip($folder, $destination) {
    $valid_files = get_files($folder);
    if(count($valid_files)) {       
        $zip = new ZipArchive();
        if($zip->open($destination, ZIPARCHIVE::CREATE) !== true) {
            return false;
        }
        //add the files
        foreach($valid_files as $file) {
            $zip->addFile($file,$file);
        }
        $zip->close();
        return file_exists($destination);
    }
    else
    {
        return false;
    }
}

function get_files($folder){
    $valid_files = array();
    $files = scandir($folder);
    foreach($files as $file) {
        if(substr($file, 0, 1) == "." || !is_readable($folder . '/' . $file)) {
            continue;
        }
        if(is_dir($file)){
            array_merge($valid_files, get_files($folder . '/' . $file));
        } else {
            $valid_files[] = $folder . '/' . $file;
        }
    }
    return $valid_files;
}

I'm calling it like this so it should really not be a directory:

$dest = "backups/" . time() . "_backup.zip";
if(file_exists($dest)){
    if(is_dir($dest)) {
        rmdir($dest);
    } else {
        unlink($dest);  
    }
}
create_zip('crawler/out', $dest);

Maybe someone here can help me with this. Thank you!

Simon

Simon
  • 52
  • 1
  • 1
  • 6

2 Answers2

10

In this case, the directory is not zip archive, but the file that is added to it.

Try adding this before adding the file:

if (file_exists($file) && is_file($file))

And change the filename instead of the filepath in this place:

$zip->addFile($file,$file);

onmotion
  • 173
  • 2
  • 8
  • What kind of language is it? JS? If so, may be you should use JSZip? The thread is about ZipArchive PHP extension. – onmotion Aug 07 '18 at 10:12
  • No its C#. I got a solution for that. But now concern here is "DownloadToStreamAsync" taking to much time for large size file. – Md Aslam Aug 07 '18 at 10:36
  • `is_file` implies that `file_exists`... you don't need both. You can think of: `is_file = file_exists() and it is a file` and `is_dir = file_exists() and it is a directory`.. (yes, in php file_exists() returns true for directories) – Christian Sep 06 '22 at 12:39
-5

... also; a behaviour change from PHP 7. If you have sub-folders in the folder you want to zip:

enter image description here

Brainmaniac
  • 2,203
  • 4
  • 29
  • 53