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

眉间皱痕 提交于 2019-12-11 06:38:19

问题


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




回答2:


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



来源:https://stackoverflow.com/questions/43334411/ziparchiveclose-read-error-is-a-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!