function FileSystem::deleteRecursive

Same name and namespace in other branches
  1. 8.9.x core/lib/Drupal/Core/File/FileSystem.php \Drupal\Core\File\FileSystem::deleteRecursive()
  2. 10 core/lib/Drupal/Core/File/FileSystem.php \Drupal\Core\File\FileSystem::deleteRecursive()
  3. 11.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 352

Class

FileSystem
Provides helpers to operate on files and stream wrappers.

Namespace

Drupal\Core\File

Code

public function deleteRecursive($path, callable $callback = NULL) {
    if ($callback) {
        call_user_func($callback, $path);
    }
    if (is_dir($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.