How can PHP users prevent an infinite loop when copying folders?
To prevent an infinite loop when copying folders in PHP, users can keep track of the folders that have been copied using an array. Before copying a folder, check if it has already been copied to avoid duplicating the process.
function copyFolder($source, $destination, &$copiedFolders = array()) {
if (in_array($source, $copiedFolders)) {
return;
}
$copiedFolders[] = $source;
// Copy the folder contents here
foreach (scandir($source) as $item) {
if ($item == '.' || $item == '..') {
continue;
}
$itemSource = $source . DIRECTORY_SEPARATOR . $item;
$itemDestination = $destination . DIRECTORY_SEPARATOR . $item;
if (is_dir($itemSource)) {
copyFolder($itemSource, $itemDestination, $copiedFolders);
} else {
copy($itemSource, $itemDestination);
}
}
}
// Usage
copyFolder('/path/to/source/folder', '/path/to/destination/folder');