Home >Backend Development >PHP Tutorial >PHP clears (delete) the files in the specified directory without deleting the directory folder implementation code, _PHP tutorial
In web development, we may encounter situations where we need to clear all files in a certain directory, but do not delete the subdirectories under this directory (of course, the deleted root directory will not be deleted). So how do you deal with this method of deleting only files but not directories? The blogger below will share with you a better solution to this problem. Look at the following function:
/*删除指定目录下的文件,不删除目录文件夹*/ function delFile($dirName){ if(file_exists($dirName) && $handle=opendir($dirName)){ while(false!==($item = readdir($handle))){ if($item!= "." && $item != ".."){ if(file_exists($dirName.'/'.$item) && is_dir($dirName.'/'.$item)){ delFile($dirName.'/'.$item); }else{ if(unlink($dirName.'/'.$item)){ return true; } } } } closedir( $handle); } }