First Paste code:
Copy Code code as follows:
<?php
function Delfile ($dirName) {
if ($handle = Opendir ("$dirName")) {
while (($item = Readdir ($handle))!=false) {
if ($item!= "." && $item!= "...") {
if (Is_dir ("$dirName/$item")) {
Delfile ("$dirName/$item");
Else unlink ("$dirName/$item");
}
}
Closedir ($handle);
}
?>
<?php
Delfile ('/home/sources ');
?>
Explain several functions first:
Opendir (): The function opens a directory handle that can be used by Closedir (), Readdir (), and Rewinddir ().
If successful, the function returns a directory stream, otherwise it returns false and an error. You can hide the output of an error by adding "@" in front of the function name. For example $dir=@ opendir ("image");
Readdir (): Returns an entry in a table of contents handle opened by the Opendir function that returns the file names in the folder sequentially in the order that they are sorted in the file system.
Id_dir (): detects whether the parameter file is a directory, or returns TRUE.
Un_link (): Deletes the development document.
So the idea of program execution is: The function calls the home directory, and then sequentially detects if each file is a directory, recursively calls the function if it is a directory, and deletes the file that is not a directory until all the files have been traversed.
This program only implements the deletion of the contents of the folder, and does not delete the folder itself, if you want to do this, add the following code to:
Copy Code code as follows: