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
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.
}
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
bool

Returns true if the directory is removed.


        
On this page

Search results