1. <?php
  2. /**
  3. * Flattens a directory structure.
  4. *
  5. * @param string $root The root directory to flatten.
  6. * @param string $destination The destination directory.
  7. * @return bool True on success, false on failure.
  8. */
  9. function flattenDirectory(string $root, string $destination): bool
  10. {
  11. if (!is_dir($root)) {
  12. error_log("Error: Root directory '$root' does not exist.");
  13. return false;
  14. }
  15. if (!is_dir($destination)) {
  16. if (!mkdir($destination, 0777, true)) {
  17. error_log("Error: Could not create destination directory '$destination'.");
  18. return false;
  19. }
  20. }
  21. $files = scandir($root);
  22. if ($files === false) {
  23. error_log("Error: Could not scan directory '$root'.");
  24. return false;
  25. }
  26. foreach ($files as $file) {
  27. if ($file == '.' || $file == '..') {
  28. continue;
  29. }
  30. $sourcePath = $root . '/' . $file;
  31. $destinationPath = $destination . '/' . $file;
  32. if (is_dir($sourcePath)) {
  33. // Recursive call for subdirectories
  34. if (!flattenDirectory($sourcePath, $destinationPath)) {
  35. return false; // Propagate error
  36. }
  37. } else {
  38. // Copy the file
  39. if (copy($sourcePath, $destinationPath)) {
  40. //echo "Copied: $sourcePath to $destinationPath\n"; //Uncomment for debugging
  41. } else {
  42. error_log("Error: Could not copy '$sourcePath' to '$destinationPath'.");
  43. return false; //Propagate error
  44. }
  45. }
  46. }
  47. return true;
  48. }
  49. //Example Usage (uncomment to test)
  50. /*
  51. $rootDirectory = '/path/to/your/directory'; // Replace with your root directory
  52. $destinationDirectory = '/path/to/your/destination'; // Replace with your destination directory
  53. if (flattenDirectory($rootDirectory, $destinationDirectory)) {
  54. echo "Directory flattened successfully.\n";
  55. } else {
  56. echo "Directory flattening failed.\n";
  57. }
  58. */
  59. ?>

Add your comment