<?php
/**
* Flattens a directory structure.
*
* @param string $root The root directory to flatten.
* @param string $destination The destination directory.
* @return bool True on success, false on failure.
*/
function flattenDirectory(string $root, string $destination): bool
{
if (!is_dir($root)) {
error_log("Error: Root directory '$root' does not exist.");
return false;
}
if (!is_dir($destination)) {
if (!mkdir($destination, 0777, true)) {
error_log("Error: Could not create destination directory '$destination'.");
return false;
}
}
$files = scandir($root);
if ($files === false) {
error_log("Error: Could not scan directory '$root'.");
return false;
}
foreach ($files as $file) {
if ($file == '.' || $file == '..') {
continue;
}
$sourcePath = $root . '/' . $file;
$destinationPath = $destination . '/' . $file;
if (is_dir($sourcePath)) {
// Recursive call for subdirectories
if (!flattenDirectory($sourcePath, $destinationPath)) {
return false; // Propagate error
}
} else {
// Copy the file
if (copy($sourcePath, $destinationPath)) {
//echo "Copied: $sourcePath to $destinationPath\n"; //Uncomment for debugging
} else {
error_log("Error: Could not copy '$sourcePath' to '$destinationPath'.");
return false; //Propagate error
}
}
}
return true;
}
//Example Usage (uncomment to test)
/*
$rootDirectory = '/path/to/your/directory'; // Replace with your root directory
$destinationDirectory = '/path/to/your/destination'; // Replace with your destination directory
if (flattenDirectory($rootDirectory, $destinationDirectory)) {
echo "Directory flattened successfully.\n";
} else {
echo "Directory flattening failed.\n";
}
*/
?>
Add your comment