PHP custom function to recursively delete files and directories

  • 2020-03-31 20:59:37
  • OfStack

 
 
//Remove files and directories recursively
//Example: del_dir ('.. / cache/'); Note: return of/is required
//The wok type forces the directory to be deleted. True is,false is not
 
function del_dir ($dir,$type=true) 
{ 
$n=0; 
if (is_dir($dir)) { 
if ($dh = opendir($dir)) { 
while (($file = readdir($dh)) !== false) { 
//.svn ignores SVN version control information
if ( $file == '.' or $file =='..' or $file == '.svn') 
{ 
continue; 
} 
if (is_file ($dir.$file)) 
{ 
unlink($dir.$file); 
$n++; 
} 
if (is_dir ($dir.$file)) 
{ 
del_dir ($dir.$file.'/'); 
if ($type) 
{ 
$n++; 
rmdir($dir.$file.'/'); 
} 
} 
} 
} 
closedir($dh); 
} 
return $n; 
} 

Related articles: