Paulund

PHP Delete Directory and Files In Directory

In PHP if you want to delete a directory there is security against deleting a directory which has files in it. Therefore you need to delete all the files in the folder before you can delete the directory. Below is a small function which will look in a directory if there are files in it they will be deleted and then the directory will be deleted. This function will even delete sub-directories. You can expand on this function by adding extra logic to see if the $dirname isn't a directory to simply delete the file.

PHP Function To Delete Directory And Files

Just pass the function the directory path you want to delete. This first checks to see if this directory exists, if it does exist it will open the directory so we can check to see if any files exist in the directory. If files do exist then it will loop through all the files except the . and .. files and delete them by using the unlink function. After all the files have been deleted then it can remove the directory by using the rmdir function.


<?php
function delete_directory($dirname) {
         if (is_dir($dirname))
           $dir_handle = opendir($dirname);
	 if (!$dir_handle)
	      return false;
	 while($file = readdir($dir_handle)) {
	       if ($file != "." && $file != "..") {
	            if (!is_dir($dirname."/".$file))
	                 unlink($dirname."/".$file);
	            else
	                 delete_directory($dirname.'/'.$file);
	       }
	 }
	 closedir($dir_handle);
	 rmdir($dirname);
	 return true;
}
?>

Cleaner Version By Lewis Cowles

After seeing this PHP snippet Lewis went away and improved the code by reducing it to only 9 lines of code. This is great when people take these snippets and improve them as it helps everyone learn a bit more about the code. Here's the snippet that Lewis was able to come up with.


<?php

delete_files('/path/for/the/directory/');

/* 
 * php delete function that deals with directories recursively
 */
function delete_files($target) {
    if(is_dir($target)){
        $files = glob( $target . '*', GLOB_MARK ); //GLOB_MARK adds a slash to directories returned
        
        foreach( $files as $file ){
            delete_files( $file );      
        }
      
        rmdir( $target );
    } elseif(is_file($target)) {
        unlink( $target );  
    }
}
?>