How to delete all files in the directory (keep the top level directory)
I want to delete directories and files in a directory, but keep the most advanced directory. How to say, to delete all directories and files under/upload/, but keep the/upload directory.
The following function will also remove the/upload directory
PHP Code
function Deldir ($dir) { //delete files under directory: $dh =opendir ($dir); while ($file =readdir ($DH)) { if ($file! = "." && $file! = "...") { $fullpath = $dir. " /". $file; if (!is_dir ($fullpath)) { unlink ($fullpath); } else { deldir ($fullpath);}} } Closedir ($DH); Delete current folder: if (RmDir ($dir)) { return true; } else { return false;} }
------Solution--------------------
Comments are written on:
PHP Code
Delete current folder:/* if (rmdir ($dir)) {return true; } else {return false; }*/
------Solution--------------------
PHP Code
function Deldir ($dir) {//delete files under directory: $dh =opendir ($dir); while ($file =readdir ($DH)) {if ($file! = "." && $file! = "...") {$fullpath = $dir. " /". $file; if (!is_dir ($fullpath)) {unlink ($fullpath); } else {deldir ($fullpath); }}} closedir ($DH);}
------Solution--------------------
PHP Code
function Deldir ($dir) {$t = array (); $DH = Opendir ($dir); while ($file =readdir ($DH)) {if ($file! = "." && $file! = "...") {$fullpath = $dir. " /". $file; if (!is_dir ($fullpath)) {unlink ($fullpath); } else {deldir ($fullpath); $t [] = $fullpath;//Because the directory is occupied, it cannot be deleted. Save Up}}} closedir ($DH); if ($t) array_map (' RmDir ', $t);//delete all subdirectories}
------Solution--------------------
Or when the directory is deleted to determine whether upload is not deleted
------Solution--------------------
In your original function
} else {
Deldir ($fullpath);//The return value of Deldir is not undertaken here
}
There is no point in returning. So I didn't write back
If you need to return to do this
PHP code
function Deldir ($dir) {$t = array (); $r = true; $DH = Opendir ($dir); while ($file =readdir ($DH)) {if ($file! = "." && $file! = "...") {$fullpath = $dir. " /". $file; if (!is_dir ($fullpath)) {unlink ($fullpath); } else {$r &= deldir ($fullpath); $t [] = $fullpath;//Because the directory is occupied, it cannot be deleted. Save Up}}} closedir ($DH); if ($t) foreach ($t as $f) $r &= rmdir ($f);//delete all subdirectories return $r;}