PHP removes non empty directory function code summary

  • 2020-05-27 04:39:54
  • OfStack

With this little program, PHPer does not have to manually delete the directory files on your computer. You can use this function when you practice PHP directory file operation.

Code 1:

<?php 
function d_rmdir($dirname) {   // Delete the non-empty directory  
if(!is_dir($dirname)) { 
return false; 
} 
$handle = @opendir($dirname); 
while(($file = @readdir($handle)) !== false){ 
if($file != '.' && $file != '..'){ 
$dir = $dirname . '/' . $file; 
is_dir($dir) ? d_rmdir($dir) : unlink($dir); 
} 
} 
closedir($handle); 
return rmdir($dirname) ; 
} 
if(d_rmdir("./temp")) 
 echo "succes"; 
else 
 echo "false"; 
?>


The second one is from the manual :)

Code 2:

<?php
 
functionremove_directory($dir){
 if($handle=opendir("$dir")){
 while(false!==($item=readdir($handle))){
  if($item!="."&&$item!=".."){
   if(is_dir("$dir/$item")){
    remove_directory("$dir/$item");
   }else{
    unlink("$dir/$item");
    echo"removing$dir/$item<br> ";
   }
  }
 }
 closedir($handle);
 rmdir($dir);
 echo"removing$dir<br> ";
 }
}

The third one is collected by codebit.cn, which is better than the manual

Code 3:


functionremoveDir($dirName)
{
  if(!is_dir($dirName))
  {
    returnfalse;
  }
  $handle=@opendir($dirName);
  while(($file=@readdir($handle))!==false)
  {
    if($file!='.'&&$file!='..')
    {
      $dir=$dirName.'/'.$file;
      is_dir($dir)?removeDir($dir):@unlink($dir);
    }
  }
  closedir($handle);  
  returnrmdir($dirName);
}
?>

Related articles: