Please wait for 15 seconds...

Friday, 20 September 2013



We often face this problem. Some techsirius regular readers asked me this question that how to remove all files and sub-directories of a directory. I just created this script to accomplish this task. Please do not forget to leave your feedback. Now lets get started.

Just copy below code and call the method/function del_files_n_dirs()


function list_files( $folder = '', $levels = 100 ){
    if(empty($folder))
        return false;
    if(!$levels)
        return false;
 
    $files = array();
    if($dir=@opendir($folder)){
        while(($file = readdir( $dir )) !== false ) {
            if(in_array($file, array('.', '..')))
                continue;
            if(is_dir( $folder . '/' . $file )){
                $files2 = list_files( $folder . '/' . $file, $levels - 1);
                if($files2)
                    $files = array_merge($files, $files2);
                else
                    $files[] = $folder . '/' . $file . '/';
            }
            else{
                $files[] = $folder . '/' . $file;
            }
        }
    }
    @closedir( $dir );
    return $files;
}
function del_files_n_dirs($base_dir, $delete_root_dir=TRUE){
    $files = list_files($base_dir);

    $dirs = array();
    foreach($files as $file){
if(is_file($file))
unlink($file);
        // now collect all directories in an array to delete these one by one
        if(substr_count($file, '/')){
            $file_arr = explode('/', $file);
            array_pop($file_arr);
            foreach($file_arr as $key=>$value){
                $dir_path = implode('/', $file_arr);
                if(($dir_path != NULL) AND (is_dir($dir_path)) AND (!in_array($dir_path, $dirs))){
                    if(!$delete_root_dir){
                        if($dir_path!=$base_dir)
                            $dirs[] = $dir_path;
                    }
                    else
                        $dirs[] = $dir_path;
                }
                array_pop($file_arr);
            }
        }
    }
    usort($dirs, function($a, $b){
        return strlen($b)-strlen($a);
    });
    foreach($dirs as $dir){
        rmdir($dir);
    }
}

And now just call del_files_n_dirs()  method

del_files_n_dirs($base_dir);

  • The first parameter is the directory path that you want to delete.
Note: If you do not want to delete the main directory then pass the second parameter as FALSE
    del_files_n_dirs($base_dir, FALSE);

    Posted by Atul Prasad Gupta

    0 comments:

    Post a Comment

    Subscribe Techsirius

    Techsirius on Facebook