Using php programs to delete directories and files has many advantages over using ftp to delete files. First, ftp is troublesome, and ftp deletion is slow when a large number of files are deleted. In addition, the program only wants to delete the files under the folder, while retaining the directory structure can be easily implemented using php, for example, it is much easier to clear the generated logs and caches by using programs.
Step 1: PHP obtains all the files and folders under the Directory.
| The code is as follows: |
Copy code |
|
<? Php
$ Dir = "D:/"; // directory to be retrieved
Echo "*********** obtain all files and folders in the directory ************
// First determine whether the specified path is a folder
If (is_dir ($ dir )){
If ($ dh = opendir ($ dir )){
While ($ file = readdir ($ dh ))! = False ){
// The full path of the file name contains the file name
$ FilePath = $ dir. $ file;
// Obtain the file modification time
$ Fmt = filemtime ($ filePath );
Echo "<span style = 'color: #666 '> (". date ("Y-m-d H: I: s", $ fmt ). ") </span> ". $ filePath. "<br/> ";
}
Closedir ($ dh );
}
}
?> |
Step 2: delete the directory and all files in the directory
| The code is as follows: |
Copy code |
|
Function delDirAndFile ($ dirName ){
If ($ handle = opendir ("$ dirName ")){
While (false! ==( $ Item = readdir ($ handle ))){
If ($ item! = "." & $ Item! = ".."){
If (is_dir ("$ dirName/$ item ")){
DelDirAndFile ("$ dirName/$ item ");
} Else {
If (unlink ("$ dirName/$ item") echo "deleted files: $ dirName/$ item <br/> n ";
}
}
}
Closedir ($ handle );
If (rmdir ($ dirName) echo "successfully deleted Directory: $ dirName <br/> n ";
}
}
|
Step 2: delete the files under the Directory. Do not delete the directory.
| The code is as follows: |
Copy code |
|
Function delFileUnderDir ($ dirName ){
If ($ handle = opendir ("$ dirName ")){
While (false! ==( $ Item = readdir ($ handle ))){
If ($ item! = "." & $ Item! = ".."){
If (is_dir ("$ dirName/$ item ")){
DelFileUnderDir ("$ dirName/$ item ");
} Else {
If (unlink ("$ dirName/$ item") echo "deleted files: $ dirName/$ item <br/> n ";
}
}
}
Closedir ($ handle );
}
} |
Summary
In this case, we first start to get all the files and directories in the directory and then delete them.