Eliminar contenidos de directorio y contenidos de subdirectorios

He configurado algo de PHP para eliminar un directorio, su contenido y cualquier subdirectorio y sus contenidos ... Soy nuevo en PHP, así que definitivamente estoy haciendo algo MAL o estoy haciendo algo de la manera más ineficiente.

Buscando algunas referencias o sugerencias sobre cómo hacerlo mejor ...

Por cierto, este código funciona bien. Utilizando PHP 5.3.8.

chmod($main_dir, 0755);
if ($handle = opendir($main_dir)) {
    while (false !== ($entry = readdir($handle))) { 
        $absolute_path = $main_dir.'/'.$entry;
        if ($entry != "." && $entry != "..") {      
            chmod($absolute_path, 0755);
            unlink($absolute_path);

            //check if any folders exist, then delete files within
            if (file_exists($absolute_path) && is_dir($absolute_path)) {
                if ($child_handle = opendir($absolute_path)) {
                    while (false !== ($child_entry = readdir($child_handle))) {             
                    $child_absolute_path = $absolute_path.'/'.$child_entry;
                        if ($child_entry != "." && $child_entry != "..") {              
                            chmod($child_absolute_path, 0755);
                            unlink($child_absolute_path);
                        }
                    }
                    closedir($child_handle);
                }
            }
            rmdir($absolute_path);
        }
    }
    closedir($handle);
}
rmdir($main_dir);

¿Alguna idea? ¡Muy apreciado! Estoy usando PHP 5.3.8

Respuestas a la pregunta(1)

Su respuesta a la pregunta