Created
October 9, 2020 16:42
-
-
Save relliv/b7ea71c195b705a6b8fc67377cb08c45 to your computer and use it in GitHub Desktop.
Delete folder and contains with recursive way
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// target directory path | |
$target = __DIR__.'/./thumbs'; | |
/** | |
* Delete folder and contents recursively | |
* | |
* @param string $target: target dir path | |
* @return bool|null | |
* | |
* Source: https://stackoverflow.com/a/3349792/6940144 | |
*/ | |
function deleteFolder($target){ | |
if (file_exists($target)){ | |
$it = new RecursiveDirectoryIterator($target, RecursiveDirectoryIterator::SKIP_DOTS); | |
$files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST); | |
foreach($files as $file) { | |
$file->isDir() ? rmdir($file->getRealPath()) : unlink($file->getRealPath()); | |
} | |
return rmdir($target); | |
} | |
return null; | |
} | |
//example usage | |
$delete = deleteFolder($target); | |
if ($delete === null){ | |
echo 'Target directory not found'; | |
} else if ($delete === false){ | |
echo 'Target directory not found or operation failed'; | |
} else { | |
echo 'Folder and contains deleted!'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment