PHP function to delete directories

In PHP, if you want to delete a directory, for security, first you must delete all its contents, whether they are files or other directories. for this purpose you need a recursive function that allows you to delete the files of each directory inside it and its files.

Below you can see a function specially created to delete directories with PHP and that, before proceeding to delete the desired directory, it will check if it contains any type of information (files or directories) and delete it.

function borrar_directorio($dirname) {
	//si es un directorio lo abro
         if (is_dir($dirname))
           $dir_handle = opendir($dirname);
        //si no es un directorio devuelvo false para avisar de que ha habido un error
	 if (!$dir_handle)
	      return false;
        //recorro el contenido del directorio fichero a fichero
	 while($file = readdir($dir_handle)) {
	       if ($file != "." && $file != "..") {
                   //si no es un directorio elemino el fichero con unlink()
	            if (!is_dir($dirname."/".$file))
	            else //si es un directorio hago la llamada recursiva con el nombre del directorio
	//elimino el directorio que ya he vaciado
	 return true;


  • Deleting the directory with PHP step by step
  • Directory deletion conclusion in PHP

Deleting the directory with PHP step by step

In order to understand what this function does, you need to know what a recursive function is and how it works. If you don’t feel like reading the long explanation of the wikipedia, comment above that it is a programming function that calls itself one or more times.

On the other hand, we are going to comment on the main functions used in this php snippet:

  1. Open the directory with PHP so that you can traverse it with opendir().
  2. retrieve one by one items it contains with the php readdir() function. This function will also return us false if there are no more items to read.
  3. Delete the files we find with php function unlink().
  4. If we find a directory instead of a file, we go through it, empty it and delete it with the same snippet function: delete_directory($directory).
  5. closedir() to close the open directory, free up resources, and allow for subsequent deletion without errors.
  6. Delete directory with PHP function specific for it rmdir($dirname).

Directory deletion conclusion in PHP

I hope this php function to delete directories It has been useful to you and that you integrate it from now on into your utility resources. These types of functions together make up a perfect set of utilities that I, if I were you, would add to a class like FileHelpers along with other related

Finally, if you have come to read this far, thank you! And if you liked it, help us by sharing this publication so that it reaches other web programmers and we can continue creating useful and free content.

Leave a Reply