In PHP if you want to delete a directory there is security in deleting the directory with files in it. So you need to delete all the files in the folder before you can delete the directory. Below is a small function that will appear in the directory if any files in it will be deleted and the directory will be deleted. This operation will also delete the directions below. You can extend this function by adding additional logic to see that the $ directory name name is not a guide to simply delete a file.

Sometimes, we need to delete all files and directions in the directory using php code. so in this post I will help you how to delete a folder and all the content within that folder.

Example 1:

function delete_folder($dir_name) {
         if (is_dir($dir_name))
           $dir_handle = opendir($dir_name);
     if (!$dir_handle)
          return false;
     while($file_name = readdir($dir_handle)) {
           if ($file_name != "." && $file_name != "..") {
                if (!is_dir($dir_name."/".$file_name ))
                     unlink($dir_name."/".$file_name );
                     delete_folder($dir_name.'/'.$file_name );
     return true;

Example 2:

$folder_name = 'photos';
removeFiles($folder_name );
function removeFiles($target_file) {
        $files = glob( $target_file . '*', GLOB_MARK );
        foreach( $files as $file ){
            removeFiles( $file );      
        rmdir( $target_file);
    } elseif(is_file($target_file)) {
        unlink( $target_file);