Oihana PHP

deleteDirectory.php

Table of Contents

Functions

deleteDirectory()  : bool
Deletes a directory recursively.

Functions

deleteDirectory()

Deletes a directory recursively.

deleteDirectory(string|array<string|int, mixed>|null $path[, bool $assertable = true ][, bool $isReadable = true ][, bool $isWritable = true ]) : bool

Symbolic links are removed, never followed. A link met in the tree is unlinked, whether it points to a directory or to a file, and whether its target still exists or not. The target is left untouched: nothing is ever deleted through a link. The same holds for $path itself — if $path is a link to a directory, the link alone is removed and the directory it points to is kept, so the call does not recurse at all.

Parameters
$path : string|array<string|int, mixed>|null

Directory or segments to remove.

$assertable : bool = true

Whether to validate the resulting path. Defaults to true.

$isReadable : bool = true

Check if the directory is readable (Default true).

$isWritable : bool = true

Check if the directory is writable (Default false).

Tags
throws
DirectoryException

If the directory path is null, empty, or if the directory cannot be deleted.

example

Create a temporary directory structure and then delete it.

$baseDir = sys_get_temp_dir() . '/temp_dir_to_delete';
$subDir = $baseDir . '/nested_dir';
mkdir($subDir, 0777, true); // Create nested directories
file_put_contents($baseDir . '/file.txt', 'content');

try
{
    if ( deleteDirectory( $baseDir ) )
    {
          // The directory and all its contents are now removed.
          // is_dir($baseDir) will return false.
    }
}
catch (DirectoryException $e)
{
    // Handle potential permission errors or other issues.
    echo "Error: " . $e->getMessage();
}

Using an array to specify the path to delete.

$parentDir = sys_get_temp_dir();
$dirName = 'another_temp_dir';
mkdir($parentDir . '/' . $dirName);
try
{
    // The path will be resolved to '/path/to/temp/another_temp_dir' and deleted.
    if (deleteDirectory([$parentDir, $dirName]))
    {
        // The directory is now removed.
    }
}
catch (DirectoryException $e)
{
    // Handle error.
}

A link inside the tree goes away with the tree, its target stays.

mkdir( '/tmp/tree' ) ;
mkdir( '/tmp/outside' ) ;
file_put_contents( '/tmp/outside/keepme.txt' , 'content' ) ;
symlink( '/tmp/outside' , '/tmp/tree/linked' ) ;

deleteDirectory( '/tmp/tree' ) ;

// is_dir('/tmp/tree') is false, '/tmp/outside/keepme.txt' is still there.
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
bool —

Returns true if the directory is removed.

On this page

Search results