PHP recursive file and directory deletion functions

Source: Internet
Author: User
Tags parent directory


A recursive function is a self-called function that calls itself directly or indirectly in the function body. However, you must set the self-called conditions. If the conditions are met, the function itself is called, if not, terminate the self-calling of the function, and then return the main control right of the current process to the previous function for execution.

Let's look at a classic recursive delete function.

Function: delete all files under the Directory and delete the directory.

Function code:

The code is as follows: Copy code

<? Php
Function deldir ($ dirname ){
If (file_exists ($ dirname) {// first checks whether the directory is valid
$ Dir = opendir ($ dirname); // open the directory with opendir
While ($ filename = readdir ($ dir) {// read contents in the directory cyclically using readdir
If ($ filename! = "." & $ Filename! = "..") {// Exclude ".." and ".." special directories
$ File = $ dirname. "/". $ filename;
If (is_dir ($ file) {// determines whether the directory is used. if yes, it calls itself.
Deldir ($ file); // recursively delete sub-directories
} Else {
@ Unlink ($ file); // delete an object
            } 
          } 
        } 
Closedir ($ dir); // close the file operation handle
Rmdir ($ dirname); // delete a directory
    } 

?>

Example: Public is a folder with many folders and files. Call deldir ($ dirname) to delete it.

<? Php
$ Dir = 'public'; // input a folder path.
Deldir ($ dir); // call a function
?>

Note: First, judge whether the Public exists. If yes, open the Public, and then use readdir to read the content in the Public directory cyclically. If yes ". "and ".. "These two special directories are excluded. If a folder is encountered, it calls its own processing until the conditions are not met. Files are deleted directly. Finally, the system jumps out and deletes the Public.


Instance 2: delete non-empty directories

The code is as follows: Copy code

/*
User-defined deletion function, which can delete files and recursively delete folders
*/
Function my_del ($ path)
{
If (is_dir ($ path ))
 {
$ File_list = scandir ($ path );
Foreach ($ file_list as $ file)
   {
If ($ file! = '.' & $ File! = '..')
    {
My_del ($ path. '/'. $ file );
    }
   }
@ Rmdir ($ path); // This method does not need to judge whether the folder is empty, because no matter whether the folder is empty at the beginning, it is empty when it arrives here
 }
Else
 {
@ Unlink ($ path); // it is best to use @ to block the warning errors in these two places.
 }

}


$ Path = 'd:/technical documentation-replica '; // folder to be deleted

// If the php file is not ANSI but UTF-8 mode and the folder to be deleted contains Chinese characters, transcoding is required before calling the function
// $ Path = iconv ('utf-8', 'gb2312', $ path );

My_del ($ path );

Example 3: The cause of failure is displayed.

The code is as follows: Copy code
<? Php
Functiondeletedir ($ dir ){
If (! Handle = @ opendir ($ dir) {// check whether the directory to be opened exists
Die ("this directory is not available ");
}   
While (false! ==( $ File = readdir ($ handle ))){
If ($ file! = "." & $ File! = "..") {// Exclude the current directory and parent directory
$ File = $ dir. DIRECTORY_SEPARATOR. $ file;
If (is_dir ($ file )){
Deletedir ($ file );
} Else {
If (@ unlink ($ file )){
Echo "file <B> $ file </B> is successfully deleted. <Br> ";
} Else {
Echo "file <B> $ file </B> failed to be deleted! <Br> ";
}   
}   
}   
If (@ rmdir ($ dir )){
Echo "directory <B> $ dir </B> is successfully deleted. <Br> n ";
} Else {
Echo "directory <B> $ dir </B> failed to be deleted! <Br> n ";
}   
}   
 
// Test the program
$ Dir = "/var/www/test ";
Deletedir ($ dir );
?>

 
Create a write folder and file test in the/var/www/test folder
Shell> touchaaa
Shell> touchbbb
Shell> touchccc
Shell> toucheee
Shell> touchffff
Shell> mkdir111
Shell> mkdir222
Shell> mkdir333
Create and write files in the 111,222,333 folder, and then grant them permissions.
Shell> chown [url] www. www [/url] test-R

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.