1. <?php
  2. /**
  3. * Backs up queue files for manual execution with limited memory.
  4. *
  5. * @param string $queue_dir The directory containing the queue files.
  6. * @param string $backup_dir The directory to store the backups.
  7. * @param int $max_filesize Maximum size of each backup file in bytes (to limit memory).
  8. */
  9. function backupQueues(string $queue_dir, string $backup_dir, int $max_filesize): void
  10. {
  11. if (!is_dir($queue_dir)) {
  12. error_log("Error: Queue directory '$queue_dir' does not exist.");
  13. return;
  14. }
  15. if (!is_dir($backup_dir)) {
  16. mkdir($backup_dir, 0777, true); // Create backup directory if it doesn't exist
  17. if (!is_dir($backup_dir)) {
  18. error_log("Error: Could not create backup directory '$backup_dir'.");
  19. return;
  20. }
  21. }
  22. $files = scandir($queue_dir);
  23. if ($files === false) {
  24. error_log("Error: Could not scan queue directory '$queue_dir'.");
  25. return;
  26. }
  27. foreach ($files as $file) {
  28. if ($file == '.' || $file == '..') {
  29. continue;
  30. }
  31. $filepath = $queue_dir . '/' . $file;
  32. if (is_file($filepath)) {
  33. $filename = basename($file); // Get filename without path
  34. $backup_filepath = $backup_dir . '/' . $filename . '_' . time() . '.bak';
  35. $handle = fopen($backup_filepath, 'wb');
  36. if ($handle === false) {
  37. error_log("Error: Could not open backup file '$backup_filepath' for writing.");
  38. continue; // Skip to the next file
  39. }
  40. $file_size = filesize($filepath);
  41. if ($file_size > $max_filesize) {
  42. error_log("Warning: File '$filepath' is larger than the maximum allowed size ($max_filesize bytes). Skipping.");
  43. fclose($handle);
  44. continue;
  45. }
  46. readfile($filepath, $handle); // Copy file contents to backup
  47. fclose($handle);
  48. echo "Backed up: $filepath to $backup_filepath\n";
  49. }
  50. }
  51. }
  52. // Example usage:
  53. // backupQueues('/path/to/your/queues', '/path/to/your/backups', 1024 * 1024); // 1MB limit
  54. ?>

Add your comment