• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

WP Bitz

A curated collection of code snippets for WordPress

  • Home
  • About
  • Blog
  • Code Snippets
You are here: Home / Code Snippets / Delete directory using rmdir() in PHP even if the directory is not empty

Delete directory using rmdir() in PHP even if the directory is not empty

December 20, 2025

This post brought to you by RocketGeek, ButlerBlog, and the following:

 

function delete_directory( $dir ) {
    // Check if $dir is a directory.
    if ( ! is_dir( $dir ) ) {
        return false; // No need to continue if it's not a directory.
    }

    // Get all files and folders in the directory.
    $items = scandir( $dir );
    // Loop through items in the directory.
    foreach ( $items as $item ) {
        // Skip special entries "." (current directory) and ".." (parent directory)
        if ( $item == '.' || $item == '..' ) {
            continue;
        }
        // Build the full path of the current item.
        $path = $dir . DIRECTORY_SEPARATOR . $item;

        // If the item is a directory, call this function recursively.
        if ( is_dir( $path ) ) {
            delete_directory( $path );
        } else { // If the item is a file, delete it.
            unlink( $path );
        }
    }
    // Remove the main directory.
    return rmdir( $dir );
}

Chad Butler

Primary Sidebar

Join for free!

Get free code snippets, WordPress best practices, and practical Content Marketing advice from seasoned WordPress expert Chad Butler (butlerblog):

Recent Posts

  • Check and delete orphaned user meta in WordPress
  • Add a Database Connection to use WPDB
  • Notice: Function WP_Block_Patterns_Registry::register was called incorrectly
  • Use WP-CLI to back up your site
  • Bitnami WordPress Autoptimize cannot write to the cache directory

Copyright © 2026 · Maker Pro on Genesis Framework · WordPress · Log in