Can the rmdir() function be modified to delete a directory with contents in PHP?

The rmdir() function in PHP cannot directly remove a directory with contents. To delete a directory with contents, you need to first recursively delete all the files and subdirectories within the directory before removing the directory itself. This can be achieved using a custom function that iterates through the contents of the directory and deletes them one by one.

function deleteDirectory($dir) {
    if (!file_exists($dir)) {
        return false;
    }

    $files = array_diff(scandir($dir), array('.', '..'));

    foreach ($files as $file) {
        (is_dir("$dir/$file")) ? deleteDirectory("$dir/$file") : unlink("$dir/$file");
    }

    return rmdir($dir);
}

// Usage example
$directory = "path/to/directory";
deleteDirectory($directory);