Skip to content

Instantly share code, notes, and snippets.

@martin-klima
Created December 20, 2017 16:38
Show Gist options
  • Save martin-klima/172f81d06c414a586c17a0eae342a980 to your computer and use it in GitHub Desktop.
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
<?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