1. <?php
  2. /**
  3. * Backs up collection files.
  4. *
  5. * This script performs a one-time backup of files within collections,
  6. * with defensive checks to prevent errors and data loss.
  7. */
  8. // Configuration
  9. define('BACKUP_DIR', '/path/to/backup/directory'); // Update this!
  10. define('SOURCE_DIR', '/path/to/source/directory'); // Update this!
  11. define('EXCLUDE_PATTERNS', ['cache/', 'tmp/']); // Optional: Exclude directories
  12. // Check if required directories exist
  13. if (!is_dir(BACKUP_DIR)) {
  14. die("Error: Backup directory '$BACKUP_DIR' does not exist. Please create it.");
  15. }
  16. if (!is_dir(SOURCE_DIR)) {
  17. die("Error: Source directory '$SOURCE_DIR' does not exist. Please check the path.");
  18. }
  19. // Get current timestamp for backup directory name
  20. $timestamp = date('Y-m-d_H-i-s');
  21. $backupDir = BACKUP_DIR . $timestamp;
  22. // Create backup directory
  23. if (!mkdir($backupDir, 0777, true)) {
  24. die("Error: Could not create backup directory '$backupDir'. Check permissions.");
  25. }
  26. // Function to recursively copy files
  27. function copyFiles($source, $destination) {
  28. if (!is_dir($source)) {
  29. return; // Not a directory, do nothing
  30. }
  31. $dirIterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
  32. foreach ($dirIterator as $file) {
  33. $filePath = $file->getPathname();
  34. $relativePath = str_replace($source, '', $filePath) . '/'; // Get relative path
  35. // Exclude specified patterns
  36. $exclude = false;
  37. foreach (EXCLUDE_PATTERNS as $pattern) {
  38. if (strpos($relativePath, $pattern) === 0) {
  39. $exclude = true;
  40. break;
  41. }
  42. }
  43. if ($exclude) {
  44. continue; // Skip excluded files/directories
  45. }
  46. $destPath = $destination . $relativePath;
  47. if ($file->isDir()) {
  48. // Create destination directory if it doesn't exist
  49. if (!is_dir($destPath)) {
  50. mkdir($destPath, 0777, true);
  51. }
  52. copyFiles($filePath, $destPath); // Recursive call
  53. } else {
  54. // Copy the file
  55. if (copy($filePath, $destPath)) {
  56. //echo "Copied: $filePath to $destPath\n"; // Optional: Debug output
  57. } else {
  58. error_log("Error copying file: $filePath to $destPath");
  59. }
  60. }
  61. }
  62. }
  63. // Start backup process
  64. echo "Starting backup...\n";
  65. copyFiles(SOURCE_DIR, $backupDir);
  66. echo "Backup completed to: $backupDir\n";
  67. ?>

Add your comment