Home >Backend Development >PHP Problem >How to delete non-empty directories with php code
How to delete a non-empty directory with php code: 1. Create a PHP sample file; 2. Set the file encoding to utf8; 3. Delete the non-empty directory through a recursive function. The code is such as "function deldir ($dir){if(file_exists($dir)){$files=scandir($dir);foreach($files as $file){...}}".
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, Dell G3 computer.
How to delete non-empty directories with php code?
The code is as follows:
<?php header("Content-type: text/html; charset=utf-8"); $dir='mydir'; function deldir($dir){ if(file_exists($dir)){ $files=scandir($dir); foreach($files as $file){ if($file!='.' && $file!='..'){ $path=$dir.'/'.$file; if(is_dir($path)){ deldir($path); }else{ unlink($path); } } } rmdir($dir); return true; }else{ return false; } } if(deldir($dir)){ echo "目录删除成功!"; }else{ echo "没有目录!"; }
PHP’s deletion of non-empty directories is actually implemented using recursive functions. PHP does not have a function to directly delete non-empty directories.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to delete non-empty directories with php code. For more information, please follow other related articles on the PHP Chinese website!