Skip to content

Instantly share code, notes, and snippets.

@dovidezra
Last active April 4, 2023 11:39
Show Gist options
  • Save dovidezra/45709d6de225be72cd9fefa5e143538a to your computer and use it in GitHub Desktop.
Save dovidezra/45709d6de225be72cd9fefa5e143538a to your computer and use it in GitHub Desktop.
An example PHP script that creates a backup of files within a specified path, to be run as a cronjob once a day.
<?php
/////////////////////////////////////////////////////////////////////////////////////////////////////////
/// To run this script as a cronjob once a day, you can add a new entry to the crontab file using the ///
/// crontab -e command and specifying the desired time for the backup to be created. For example, to ////
/// run the backup script every day at midnight, you can add the following line to the crontab file: ////
/// 0 0 * * * /usr/bin/php /path/to/backup-script.php >/dev/null 2>&1 ///////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Set the path to the source directory to be backed up
$scriptPath = dirname(__FILE__);
$backupSource = $scriptPath . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'uploads';
// Set the path to the backup directory
$backupDir = $scriptPath . DIRECTORY_SEPARATOR . 'backup';
// Create the backup directory if it doesn't exist
if (!file_exists($backupDir)) {
mkdir($backupDir, 0777, true);
}
// Set the name of the backup file with the current date and time
$backupFile = 'backup-' . date('Ymd-His') . '.zip';
// Create the backup archive
$zip = new ZipArchive();
if ($zip->open($backupDir . DIRECTORY_SEPARATOR . $backupFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($backupSource));
foreach ($files as $file) {
if (!$file->isDir()) {
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($backupSource) + 1);
$zip->addFile($filePath, $relativePath);
}
}
$zip->close();
echo 'Backup created: ' . $backupDir . DIRECTORY_SEPARATOR . $backupFile . PHP_EOL;
} else {
echo 'Failed to create backup: ' . $backupDir . DIRECTORY_SEPARATOR . $backupFile . PHP_EOL;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment