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


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

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

代码:

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

希望它能解决你的问题。否则检查备份文件夹文件访问权限