php Empty (delete) the specified directory files do not delete the directory folder implementation code

  • 2021-07-18 07:25:00
  • OfStack

In the development of web, we may encounter the situation that we need to empty all files in a certain directory, but not delete the subdirectories in this directory (and certainly not delete the deleted root directory). So how do you handle this method of deleting only files but not directories? The following blogger will share with you a better solution to this problem. Look at the following function:


/* Delete files in the specified directory without deleting directory folders */
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);
	}
}

Related articles: