PHP – Delete a Directory Recursively

This below code shows you how to recursively delete a directory/folder using PHP. Let’s consider the following code:

example.php
<?php

function deleteDirectory($directory)
{
    if (!is_dir($directory)) {
        return false;
    }

    foreach (glob("{$directory}/*") as $file) {
        if (is_dir($file)) { 
            deleteDirectory($file);
        } else {
            deleteFile($file);
        }
    }
    
    rmdir($directory);
}

function deleteFile($filePath)
{
    if (is_file($filePath)) {
        return @unlink($filePath);
    }
}

The idea in the above code is that we need to delete all files in sub-directory first using deleteFile(). Then once that sub-directory is empty, we simply call rmdir() to delete it.

 

Use the function:

$dirToDelete = __DIR__ . '/test';
deleteDirectory($dirToDelete);

guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x