Skip to content

Instantly share code, notes, and snippets.

@relliv
Created October 9, 2020 16:42
Show Gist options
  • Save relliv/b7ea71c195b705a6b8fc67377cb08c45 to your computer and use it in GitHub Desktop.
Save relliv/b7ea71c195b705a6b8fc67377cb08c45 to your computer and use it in GitHub Desktop.
Delete folder and contains with recursive way
<?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