function FileSystem::deleteRecursive
Same name and namespace in other branches
- 11.x core/lib/Drupal/Core/File/FileSystem.php \Drupal\Core\File\FileSystem::deleteRecursive()
- 10 core/lib/Drupal/Core/File/FileSystem.php \Drupal\Core\File\FileSystem::deleteRecursive()
- 9 core/lib/Drupal/Core/File/FileSystem.php \Drupal\Core\File\FileSystem::deleteRecursive()
- 8.9.x core/lib/Drupal/Core/File/FileSystem.php \Drupal\Core\File\FileSystem::deleteRecursive()
Deletes all files and directories in the specified filepath recursively.
If the specified path is a directory then the function is called recursively to process the contents. Once the contents have been removed the directory is also removed.
If the specified path is a file then it will be processed with delete() method.
Note that this only deletes visible files with write permission.
Parameters
string $path: A string containing either an URI or a file or directory path.
callable|null $callback: Callback function to run on each file prior to deleting it and on each directory prior to traversing it. For example, can be used to modify permissions.
Overrides FileSystemInterface::deleteRecursive
File
-
core/
lib/ Drupal/ Core/ File/ FileSystem.php, line 340
Class
- FileSystem
- Provides helpers to operate on files and stream wrappers.
Namespace
Drupal\Core\FileCode
public function deleteRecursive($path, ?callable $callback = NULL) {
// Resolve stream wrapper URIs to local paths so that is_link() can
// detect symlinks and prevent traversal outside the target directory.
// Remote stream wrappers return FALSE from realpath(), in which case
// the original URI is kept since is_link() does not work with stream
// wrapper URIs.
if ($this->streamWrapperManager
->isValidUri($path)) {
$realpath = $this->realpath($path);
if ($realpath !== FALSE) {
$path = $realpath;
}
}
if ($callback) {
call_user_func($callback, $path);
}
// Allow broken links to be removed.
if (!file_exists($path) && !is_link($path)) {
return TRUE;
}
if (is_dir($path) && !is_link($path)) {
$dir = dir($path);
while (($entry = $dir->read()) !== FALSE) {
if ($entry == '.' || $entry == '..') {
continue;
}
$entry_path = $path . '/' . $entry;
$this->deleteRecursive($entry_path, $callback);
}
$dir->close();
return $this->rmdir($path);
}
return $this->delete($path);
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.