Two small functions implement php traversal to delete folders

Source: Internet
Author: User
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;
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.