php method to delete non-empty folders: first create a PHP sample file; then check whether there are files or folders in the directory; finally, use recursion to delete all files and folders in the directory.
The operating environment of this article: Windows 7 system, PHP version 7.1, DELL G3 computer.
PHP deletes non-empty directories/folders
Using PHP’s own file system function rmdir() often encounters a problem when deleting a directory, that is, The directory to be deleted must be empty, otherwise an error will be reported.
To delete a non-empty directory, first check if there are files or folders in the directory. If there are, recursively delete all files and folders in the directory, and then delete the directory.
The specific operations are as follows:
1. Function definition
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; } }
2. Delete directory
function doDel(){ $dir="./src/folder"; if(deldir($dir)){ echo("删除成功"); }else{ echo("删除失败"); } }
Principle description:
Check this first Is there a file in the directory? If so, if it is a folder, call this function to delete it. If it is a file, directly call unlink to delete it, and finally delete the directory.
Note:
Make sure you have permission to operate the folder
[Recommended: PHP video tutorial]
The above is the detailed content of How to delete non-empty folders in php. For more information, please follow other related articles on the PHP Chinese website!