php Instance Shared Delete All Files in Directory by Recursive Details

  • 2021-06-28 11:26:05
  • OfStack

Paste code first:


<?php
function delFile($dirName){ 
 if ($handle = opendir("$dirName")){
  while (($item = readdir($handle))!=false){
   if ($item!="." && $item!="..")  {
    if ( is_dir( "$dirName/$item" ) ) {  
             delFile( "$dirName/$item" );  
       } else unlink("$dirName/$item");
  }
 }
 closedir($handle);
}
?>

<?php
 delFile('/home/sources');
?>

Let's start with a few functions:

opendir(): The function opens a directory handle, which can be used by closedir(), readdir(), and rewinddir().

If successful, the function returns a directory stream, otherwise it returns false and an error.You can hide the output of error by prefixing the function name with'@'.For example, $dir=@ opendir ("image");

readdir(): Returns the entries in the directory handle opened by the opendir function, that is, the file names in the folders are returned sequentially in the order specified in the file system.

id_dir(): that is, to detect if the parameter file is a directory, and if it is returned to true.

un_link(): Delete the development document.

So the program execution idea is: the function calls the home directory, then sequentially detects if each file is a directory, if it is a directory, recursively calls the function, and deletes the files that are not directories until all the files have been traversed.

This program only deletes the contents of the folder, not the folder itself. To achieve this, add the following code:


rmdir($dirName);


Related articles: