ZipArchive::close(): Read error: Is a directory

2019-07-22 12:53发布

问题:

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

回答1:

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);