5

我正在尝试通过压缩所有站点来备份我的站点,然后将压缩包放入一个无法访问的文件夹中,使用 PHP 完成。我的代码是

<?php
Zip('../../', './');
function Zip($source, $destination)
{
    if (extension_loaded('zip') === true)
    { echo'a';
        if (file_exists($source) === true)
        {
            $zip = new ZipArchive();

            if ($zip->open($destination, ZIPARCHIVE::CREATE) === true)
            {
                $source = realpath($source);

                if (is_dir($source) === true)
                {
                    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

                    foreach ($files as $file)
                    {
                        $file = realpath($file);

                        if (is_dir($file) === true)
                        {
                            $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
                        }

                        else if (is_file($file) === true)
                        {
                            $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
                        }
                    }
                }

                else if (is_file($source) === true)
                {
                    $zip->addFromString(basename($source), file_get_contents($source));
                }
            }

            return $zip->close(); // The error.
        }
    }

    return false;
}
?>

但是我得到一个错误,Warning: ZipArchive::close() [ziparchive.close]: Invalid or unitialized Zip object in backup.php on line 41我已经搜索了谷歌,但没有结果。

4

2 回答 2

6

From PHP 5.2.8, this issue has started to emerge.

Try adding the FLAGS to the open method

 - ZipArchive::OVERWRITE
 - ZipArchive::CREATE
 - ZipArchive::EXCL
 - ZipArchive::CHECKCONS

This command would most probably fix the issue

$zip->open($destination, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE);

Quick and Dirtiest Fix would be this, if the above doesn't work

@$zip->close();
于 2013-07-31T15:49:18.107 回答
0

在我的情况下,目标文件夹完全丢失,这导致close().

因此,我检查目标文件夹是否存在,如果不存在,我尝试创建它。如果两个调用都失败,我会抛出一个异常。在您的情况下,将类似于以下内容:

$destinationPath = (new \SplFileInfo($destination))->getPath();
if (!is_dir($destinationPath) && !mkdir($destinationPath, 0755, true)) {
    throw new \Exception(sprintf('Destination folder "%s" is missing and cannot be created', $destinationPath));
}
于 2021-12-13T16:28:40.227 回答