Created
July 27, 2020 05:22
-
-
Save aurmil/af3311b10c09bc58dcbc16f7e6db657e to your computer and use it in GitHub Desktop.
Scheduled backup script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Backup | |
{ | |
protected $logFilePath; | |
public function __construct($logFilePath) | |
{ | |
$this->logFilePath = $logFilePath; | |
} | |
public function backup($source, $destination) | |
{ | |
$this->log("Begin backup of $source to $destination"); | |
if (!extension_loaded('zip')) { | |
$this->log('Zip extension is required'); | |
return false; | |
} | |
if (!file_exists($source)) { | |
$this->log("Source not found"); | |
return false; | |
} | |
$zip = new ZipArchive(); | |
$ret = $zip->open($destination, ZIPARCHIVE::CREATE); | |
if (true !== $ret) { | |
$this->log("Destination open error, error code: $ret"); | |
return false; | |
} | |
$source = str_replace('\\', '/', realpath($source)); | |
if (is_dir($source)) { | |
$files = new RecursiveIteratorIterator( | |
new RecursiveDirectoryIterator($source), | |
RecursiveIteratorIterator::SELF_FIRST | |
); | |
foreach ($files as $file) { | |
$file = str_replace('\\', '/', realpath($file)); | |
if (is_dir($file)) { | |
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/')); | |
} elseif (is_file($file)) { | |
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file)); | |
} | |
} | |
} elseif (is_file($source)) { | |
$zip->addFromString(basename($source), file_get_contents($source)); | |
} | |
if (!$zip->close()) { | |
$this->log("Destination close error"); | |
} | |
$this->log("End backup of $source"); | |
} | |
protected function log($message) | |
{ | |
file_put_contents( | |
$this->logFilePath, | |
date('Y-m-d H:i:s') . ' ' . $message . PHP_EOL, | |
FILE_APPEND | |
); | |
} | |
} | |
$rootDirPath = dirname(__DIR__); | |
$backupDirPath = $rootDirPath . '/backup'; | |
$backupDestDirPath = $backupDirPath . '/' . date('Y-m'); | |
$today = date('Y-m-d'); | |
$backup = new Backup($backupDirPath . '/backup.log'); | |
if (!is_dir($backupDestDirPath)) { | |
mkdir($backupDestDirPath); | |
} | |
$backup->backup("$rootDirPath/freshrss/data", "$backupDestDirPath/freshrss-$today.zip"); | |
$backup->backup("$rootDirPath/shaarli/data", "$backupDestDirPath/shaarli-$today.zip"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment