Created
December 20, 2017 16:38
-
-
Save martin-klima/172f81d06c414a586c17a0eae342a980 to your computer and use it in GitHub Desktop.
Drupal 8: Deletes all files and directories in the specified filepath recursively
This file contains 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 | |
/** | |
* Deletes all files and directories in the specified filepath recursively. | |
* | |
* @param $path | |
* @param bool $deleteDir | |
* TRUE if you need to delete also directory in $path. | |
* FALSE if you need to delete only content of dir and its subdirs. | |
* | |
* @return bool | |
* FALSE if errors. | |
*/ | |
protected function deleteDirectoryContentRecursively($path, $deleteDir = FALSE) { | |
if (is_dir($path)) { | |
$dir = dir($path); | |
while (($entry = $dir->read()) !== FALSE) { | |
if ($entry == '.' || $entry == '..') { | |
continue; | |
} | |
$entry_path = $path . '/' . $entry; | |
$this->deleteDirectoryContentRecursively($entry_path, TRUE); | |
} | |
$dir->close(); | |
if ($deleteDir) { | |
\Drupal::service('file_system')->rmdir($path); | |
} | |
return TRUE; | |
} | |
return file_unmanaged_delete($path); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment