Что означает эта ошибка в PHP: Предупреждение: ZipArchive::close(): Ошибка чтения: неверный файловый дескриптор в ()?

У меня есть PHP-скрипт для создания zip с двумя функциями:

  1. dirToArray : чтобы получить все файлы/пустые_папки в массиве
  2. create_zip : для вызова dirToArray() и создания zipArchive

Я получил странное предупреждение, которое на самом деле делает реальную ошибку, потому что мой zip-архив не создан.

Результат предупреждения

Предупреждение: ZipArchive::close(): ошибка чтения: неверный файловый дескриптор в пути/к/file.php в строке x

Кто-нибудь может объяснить мне, что означает: «Плохой файловый дескриптор»?

Это код:

диртомассив

/* to copy all file/folder names from a directory into an array*/
function dirToArray($dir_path) {
    $result = array();
    $path = realpath($dir_path);
    $objects = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path), \RecursiveIteratorIterator::SELF_FIRST);
    foreach($objects as $name => $object) {
        if( $object->getFilename() !== "." && $object->getFilename() !== "..") {
            $result[] = $object;
        }
    }
    return $result;
}

создать_zip

/* creates a compressed zip file */
function create_zip($productPath = '', $dirName = '', $overwrite = false) {
    $fullProductPath = $productPath.$dirName;
    $a_filesFolders = dirToArray( $fullProductPath );
    var_dump($a_filesFolders);
    //if the zip file already exists and overwrite is false, return false
    $zip = new \ZipArchive();
    $zipProductPath =  $fullProductPath.'.zip';
    if($zip->open( $zipProductPath ) && !$overwrite){
        $GLOBALS["errors"][] = "The directory {$zipProductPath} already exists and cannot be removed.";
    }

    //if files were passed in...
    if(is_array($a_filesFolders) && count($a_filesFolders)){
        $opened = $zip->open( $zipProductPath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE );
        if( $opened !== true ){
            $GLOBALS["errors"][] = "Impossible to open {$zipProductPath} to edit it.";
        }

        //cycle through each file
        foreach($a_filesFolders as $object) {
            //make sure the file exists
            $fileName = $object -> getFilename();
            $pathName = $object -> getPathname();
            if(file_exists($pathName)) {
                $pos = strpos($zipProductPath , "/tmp/") + 5;
                $fileDestination = substr($pathName, $pos);
                echo $pathName.'<br/>';
                echo $fileDestination.'<br/>';
                $zip->addFile($pathName,$fileDestination);
            }
            else if(is_dir( $pathName )){
                $pos = strpos($zipProductPath , "/tmp/") + 5;
                $fileDestination = substr($pathName, $pos);
                $zip->addEmptyDir($fileDestination);
            }else{
                $GLOBALS["errors"][] = "the file ".$fileName." does not exist !";
            }
        }

        //close the zip -- done!
        $zip->close();
        //check to make sure the file exists
        return file_exists($zipProductPath);
    }else{
        return false;
    }
}

person J.BizMai    schedule 31.08.2017    source источник
comment
Я предполагаю, что вызов open() терпит неудачу, а затем вы пытаетесь закрыть дескриптор, которого не существует, поскольку он не был открыт   -  person Wintermute    schedule 31.08.2017
comment
Я проверил с помощью: if( $opened !== true ){ $GLOBALS[errors][] = невозможно открыть {$zipProductPath} для редактирования.; }   -  person J.BizMai    schedule 31.08.2017
comment
Да, но это не останавливает выполнение скрипта   -  person Wintermute    schedule 31.08.2017
comment
Я сделал тесты, чтобы проверить эти случаи, я добавляю return false;... почтовый индекс открыт.   -  person J.BizMai    schedule 31.08.2017


Ответы (1)


Я нашел проблему... Меня смутила функция file_exists(), которая также определяет, существуют ли каталоги... поэтому скрипт добавил папки как файлы и допустил ошибку.

create_zip (исправлено)

/* creates a compressed zip file */
function create_zip($productPath = '', $dirName = '', $overwrite = false) {
    $fullProductPath = $productPath.$dirName;
    $a_filesFolders = dirToArray( $fullProductPath );
    var_dump($a_filesFolders);
    //if the zip file already exists and overwrite is false, return false
    $zip = new \ZipArchive();
    $zipProductPath =  $fullProductPath.'.zip';

    if($zip->open( $zipProductPath ) && !$overwrite){
        $GLOBALS["errors"][] = "The directory {$zipProductPath} already exists and cannot be removed.";
        return false;
    }
    //if files were passed in...
    if(is_array($a_filesFolders) && count($a_filesFolders)){
         $opened = $zip->open( $zipProductPath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE );
        if( $opened !== true ){
            $GLOBALS["errors"][] = "Impossible to open {$zipProductPath} to edit it.";
            return false;
        }else{
            //cycle through each file
            foreach($a_filesFolders as $object) {
                //make sure the file exists
                $fileName = $object -> getFilename();
                $pathName = $object -> getPathname();
                if(is_dir( $pathName )){ /*<-- I put on first position*/
                    $pos = strpos($zipProductPath , "/tmp/") + 5;
                    $fileDestination = substr($pathName, $pos);
                    $zip->addEmptyDir($fileDestination);
                }else if(file_exists($pathName)) {
                    $pos = strpos($zipProductPath , "/tmp/") + 5;
                    $fileDestination = substr($pathName, $pos);
                    $zip->addFile($pathName,$fileDestination);
                }
                else{
                    $GLOBALS["errors"][] = "the file ".$fileName." does not exist !";
                }
            }

            //close the zip -- done!
            $zip->close();
            //check to make sure the file exists
            return file_exists($zipProductPath);
        }
    }else{
        return false;
    }
}
person J.BizMai    schedule 31.08.2017