Two small functions are introduced to implement php traversal to recursively delete directory folders and all files in folders. In fact, php is used to delete directories and files in directories.
Today we will introduce two small functions that implement php traversal to recursively delete directory folders and all files in folders. In fact, using php to delete directories and files in directories is relatively simple, it is mainly to determine whether the file is a folder or a file during deletion. if the file is deleted directly, the folder will be deleted and the folder will be deleted. recursion is used throughout the process.
The code is as follows:
/**
* Php method for deleting folder files
* The two methods have the same names. please test them separately.
*/
Function delete_files ($ filePath ){
If (is_dir ($ filePath )){
$ File_list = scandir ($ filePath );
Foreach ($ file_list as $ file ){
If ($ file! = '.' & $ File! = '..'){
Delete_files ($ filePath. '/'. $ file );
}
}
Rmdir ($ filePath );
} Else {
Unlink ($ filePath );
}
}
Function delete_files ($ dir ){
// Delete a file in the directory
$ Dh = opendir ($ dir );
While ($ file = readdir ($ dh )){
If ($ file! = "." & $ File! = ".."){
$ Fullpath = $ dir. "/". $ file;
If (! Is_dir ($ fullpath )){
Unlink ($ fullpath );
} Else {
Delete_files ($ fullpath );
}
}
}
Closedir ($ dh );
// Delete the Directory
If (rmdir ($ dir )){
Return true;
} Else {
Return false;
}
}