PHP Delete a Directory and Containing Files Recursively

You can delete a directory using rmdir() function. But rmdir function has limitation. To remove a directory using rmdir , the directory must be blank. If a directory contains multiple directory and files then we have to apply recursive process.

Custom PHP function to delete folder including everything in it

Method 1

<?php
/**
 * @param string $dir /path/for/the/directory/ 
 * @return bool
 **/
function delete_directory( $dir )
{
  if ( is_dir( $dir ) )
  {
    
    $dir_handle = opendir( $dir );
    if( $dir_handle )
    {       
      while( $file = readdir( $dir_handle ) ) 
      {
           if($file != "." &amp;&amp; $file != "..") 
           {
                if( ! is_dir( $dir."/".$file ) )
                {
                  unlink( $dir."/".$file );
                }
                else
                {
                  delete_directory($dir.'/'.$file);
                }
                     
           }
      }
      closedir( $dir_handle );
    }
    rmdir( $dir );
    return true;
  }
  return false;
}
?>

Method 2

<?php
/**
 * @param string $dir /path/for/the/directory/
 * @return bool
 **/
function delete_directory( $dir )
{
    if( is_dir( $dir ) )
    {
      $files = glob( $dir . '*', GLOB_MARK ); //GLOB_MARK adds a slash to directories returned

      foreach( $files as $file )
      {
          delete_directory( $file );      
      }

      rmdir( $dir );
    } 
    elseif( is_file( $dir ) ) 
    {
      unlink( $dir );  
    }
}
?>

1 Comment


  1. Hello,

    I tried both of your codes but nothing happens… 🙁
    My goal is to delete a folder named “test” wich is located in : wp-content/uploads/test

    So that’s my code :

    Any help ?

    Thanks

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.