Modified variant of @XzaR solution. It does remove empty folders, when all files are deleted from them and it throws exceptions instead of returning false on errors.
function recursivelyRemoveDirectory($source, $removeOnlyChildren = true)
{
if (empty($source) || file_exists($source) === false) {
throw new Exception("File does not exist: '$source'");
}
if (is_file($source) || is_link($source)) {
if (false === unlink($source)) {
throw new Exception("Cannot delete file '$source'");
}
}
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($files as $fileInfo) {
/** @var SplFileInfo $fileInfo */
if ($fileInfo->isDir()) {
if ($this->recursivelyRemoveDirectory($fileInfo->getRealPath()) === false) {
throw new Exception("Failed to remove directory '{$fileInfo->getRealPath()}'");
}
if (false === rmdir($fileInfo->getRealPath())) {
throw new Exception("Failed to remove empty directory '{$fileInfo->getRealPath()}'");
}
} else {
if (unlink($fileInfo->getRealPath()) === false) {
throw new Exception("Failed to remove file '{$fileInfo->getRealPath()}'");
}
}
}
if ($removeOnlyChildren === false) {
if (false === rmdir($source)) {
throw new Exception("Cannot remove directory '$source'");
}
}
}