What are potential pitfalls when using rmdir to delete directories in PHP?

One potential pitfall when using rmdir to delete directories in PHP is that it will only delete empty directories. If the directory contains files or other directories, rmdir will throw an error. To avoid this issue, you can use a recursive function to delete all files and subdirectories within the directory before using rmdir to delete the empty directory.

function deleteDirectory($dir) {
    if (!file_exists($dir)) {
        return true;
    }
    
    if (!is_dir($dir)) {
        return unlink($dir);
    }
    
    foreach (scandir($dir) as $item) {
        if ($item == '.' || $item == '..') {
            continue;
        }
        
        if (!deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
            return false;
        }
    }
    
    return rmdir($dir);
}

$directory = 'path/to/directory';
deleteDirectory($directory);