将 zip 文件保存在与代码文件所在级别不同的目录中

Save zip file in a different directory than the level at which code file is present

我已经编写了一个代码来压缩给定目录的所有内容,该代码运行完美,但我想将 zip 文件保存在我调用该函数的不同目录中。

代码:

$source = realpath('application');
$address = realpath('backup');
$destination = $address . DIRECTORY_SEPARATOR . 'download.zip';

if (file_exists($destination)) {
    echo "The file $filename exists";
} else {
    echo "The file $filename does not exist";
}

Zip($source, $destination);

function Zip($source, $destination)
{
    if (!extension_loaded('zip') || !file_exists($source)) {
        return false;
    }

    $zip = new ZipArchive();
    if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
        return false;
    }

    $source = str_replace('\', '/', realpath($source));

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

        foreach ($files as $file)
        {
            $file = str_replace('\', '/', $file);

            // Ignore "." and ".." folders
            if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
                continue;

            $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();
}

没有为这段代码创建 zip 文件,但是如果我这样做

$destination = 'zip.php';

zip 文件已创建。 我该怎么做才能将文件保存在其他目录中。

您确定备份目录存在吗?然后它只会在备份文件夹中创建 Zip 文件。将以下代码附加到您现有的代码

$address = realpath('backup');
if (!file_exists($address)){
    if (!mkdir($address, 0777, true)) {
            die('Failed to create folder.');
    }
}

希望它能解决您的问题。或者检查备份文件夹文件访问权限。