<?php
/**
* Backs up collection files.
*
* This script performs a one-time backup of files within collections,
* with defensive checks to prevent errors and data loss.
*/
// Configuration
define('BACKUP_DIR', '/path/to/backup/directory'); // Update this!
define('SOURCE_DIR', '/path/to/source/directory'); // Update this!
define('EXCLUDE_PATTERNS', ['cache/', 'tmp/']); // Optional: Exclude directories
// Check if required directories exist
if (!is_dir(BACKUP_DIR)) {
die("Error: Backup directory '$BACKUP_DIR' does not exist. Please create it.");
}
if (!is_dir(SOURCE_DIR)) {
die("Error: Source directory '$SOURCE_DIR' does not exist. Please check the path.");
}
// Get current timestamp for backup directory name
$timestamp = date('Y-m-d_H-i-s');
$backupDir = BACKUP_DIR . $timestamp;
// Create backup directory
if (!mkdir($backupDir, 0777, true)) {
die("Error: Could not create backup directory '$backupDir'. Check permissions.");
}
// Function to recursively copy files
function copyFiles($source, $destination) {
if (!is_dir($source)) {
return; // Not a directory, do nothing
}
$dirIterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($dirIterator as $file) {
$filePath = $file->getPathname();
$relativePath = str_replace($source, '', $filePath) . '/'; // Get relative path
// Exclude specified patterns
$exclude = false;
foreach (EXCLUDE_PATTERNS as $pattern) {
if (strpos($relativePath, $pattern) === 0) {
$exclude = true;
break;
}
}
if ($exclude) {
continue; // Skip excluded files/directories
}
$destPath = $destination . $relativePath;
if ($file->isDir()) {
// Create destination directory if it doesn't exist
if (!is_dir($destPath)) {
mkdir($destPath, 0777, true);
}
copyFiles($filePath, $destPath); // Recursive call
} else {
// Copy the file
if (copy($filePath, $destPath)) {
//echo "Copied: $filePath to $destPath\n"; // Optional: Debug output
} else {
error_log("Error copying file: $filePath to $destPath");
}
}
}
}
// Start backup process
echo "Starting backup...\n";
copyFiles(SOURCE_DIR, $backupDir);
echo "Backup completed to: $backupDir\n";
?>
Add your comment