Home Account

remove all dirs with selected name

2013-09-12 15:41 dennis iversen

Tags: php scripts-and-functions

This PHP function removes dirs in a tree with a selected name. In this example it is all dirs with the name 'fr' as I needed to remove some translations in a piece of software.

<?php

/**
 * function will remove dirs with correct name recursively
 * @param type $start_dir 
 * @param type $remove_dir
 */
function rmdirs($start_dir, $remove_dir) {

    if (is_dir($start_dir)) {
        $fh = opendir($start_dir);
        while (($file = readdir($fh)) !== false) {

            $filepath = $start_dir . '/' . $file;
            if (strpos($file, '.')=== 0) continue;
            if ($file == $remove_dir && is_dir($filepath)) {
                echo "Removing dir: $filepath\n";
                passthru("rm -rf $filepath");
                continue;
            }
            if ( is_dir($filepath) ) {
                rmdirs($filepath, $remove_dir);
            }
        }
        closedir($fh);
    }
}

$start_dir = '.';
$files = rmdirs($start_dir, 'fr');

This page has been requested 3457 times