Home >Backend Development >PHP Tutorial >How to delete files or folders in PHP_PHP Tutorial
Sometimes we need to use PHP to delete files and folders. PHP also has functions to implement it. Let’s simply record the code below so that it can be easily copied later. Let’s take a look at the code first
<? function deldir($dir) { //先删除目录下的文件: $dh=opendir($dir); while ($file=readdir($dh)) { if($file!="." && $file!="..") { $fullpath=$dir."/".$file; if(!is_dir($fullpath)) { unlink($fullpath); } else { deldir($fullpath); } } } closedir($dh); //删除当前文件夹: if(rmdir($dir)) { return true; } else { return false; } } ?>
The unlink() function is used to delete files. Returns true if successful, false if failed. The rmdir() function is used to delete empty directories. It attempts to delete the directory specified by dir. The directory must be empty and must have appropriate permissions.
An example: delete all ".svn" folders under a certain folder (including their contents).
<?php function delsvn($dir) { $dh=opendir($dir); //找出所有".svn" 的文件夹: while ($file=readdir($dh)) { if($file!="." && $file!="..") { $fullpath=$dir."/".$file; if(is_dir($fullpath)) { if($file==".svn"){ delsvndir($fullpath); }else{ delsvn($fullpath); } } } } closedir($dh); } function delsvndir($svndir){ //先删除目录下的文件: $dh=opendir($svndir); while($file=readdir($dh)){ if($file!="."&&$file!=".."){ $fullpath=$svndir."/".$file; if(is_dir($fullpath)){ delsvndir($fullpath); }else{ unlink($fullpath); } } } closedir($dh); //删除目录文件夹 if(rmdir($svndir)){ return true; }else{ return false; } } $dir=dirname(__FILE__); //echo $dir; delsvn($dir); ?>