PHP递归备份脚本

2023-11-22

我为我的网站编写了一个基本的内容管理系统,包括一个管理面板。我了解基本的文件 IO 以及通过 PHP 进行复制,但我尝试从脚本调用备份脚本失败了。我尝试这样做:

//... authentication, other functions
for(scandir($homedir) as $buffer){
    if(is_dir($buffer)){
        //Add $buffer to an array
    }
    else{
        //Back up the file
    }
}
for($founddirectories as $dir){
    for(scandir($dir) as $b){
        //Backup as above, adding to $founddirectories
    }
}

但这似乎不起作用。

我知道我可以使用 FTP 来完成此操作,但我想要一个完全的服务器端解决方案,可以在任何地方通过足够的授权进行访问。


不过,这是一个替代方案:为什么不呢?改为压缩源目录?

function Zip($source, $destination)
{
    if (extension_loaded('zip') === true)
    {
        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();
        }
    }

    return false;
}

您甚至可以随后将其解压缩并存档相同的效果,尽管我必须说我更喜欢将备份压缩为 zip 文件格式。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PHP递归备份脚本 的相关文章

随机推荐