1. <?php
  2. /**
  3. * Backs up files specified by CLI arguments for validation.
  4. * Handles edge cases like missing arguments or invalid file paths.
  5. *
  6. * Usage: php backup_files.php <file1> <file2> ... <backup_dir>
  7. */
  8. if (count($argv) < 3) {
  9. echo "Usage: php backup_files.php <file1> <file2> ... <backup_dir>\n";
  10. exit(1); // Exit with an error code
  11. }
  12. $backupDir = $argv[count($argv) - 1]; // Last argument is the backup directory
  13. if (!is_dir($backupDir)) {
  14. if (!mkdir($backupDir, 0777, true)) {
  15. echo "Error: Could not create backup directory: $backupDir\n";
  16. exit(1);
  17. }
  18. }
  19. $filesToBackup = array_slice($argv, 1, count($argv) - 2); // Files to backup (all but the last argument)
  20. foreach ($filesToBackup as $file) {
  21. if (!file_exists($file)) {
  22. echo "Warning: File not found: $file\n";
  23. continue; // Skip to the next file
  24. }
  25. $backupFile = $backupDir . '/' . basename($file); // Backup file name
  26. if (file_put_contents($backupFile, file_get_contents($file)) === false) {
  27. echo "Error: Could not backup file: $file\n";
  28. } else {
  29. echo "Backed up: $file to $backupFile\n";
  30. }
  31. }
  32. echo "Backup process completed.\n";
  33. ?>

Add your comment