How can I ensure that all files within a directory are deleted before removing the directory itself in PHP?

To ensure that all files within a directory are deleted before removing the directory itself in PHP, you can recursively loop through the directory, delete all files, and then remove the directory itself using the rmdir() function. This approach ensures that all files are deleted before attempting to remove the directory.

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

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

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

    return rmdir($dir);
}

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