PHP

php Introduction to Create and Delete Directory Functions and Recursive Delete Directory Function Sharing


mkdir ()—New Directory

 In fact, in fact, the   Syntax: bool mkdir (string pathname [,int mode])
 In fact, in fact, the   Try to create a new 1 By  pathname  The directory specified by the.

rmdir ()—Delete Directory

 In fact, in fact, the   Syntax: bool rmdir ( string dirname )
 In fact, in fact, the   Try to delete  dirname  The directory specified by the.   The directory must be empty and have corresponding permissions. Returns if successful  TRUE If it fails, it returns
FALSE .

unlink—Delete Files

 In fact, in fact, the   Syntax: bool unlink ( string filename )
 In fact, in fact, the   Delete  filename . And  Unix C  Adj.  unlink()  Functions are similar. Returns if successful  TRUE If it fails, it returns  FALSE .

In PHP, you can easily create a new directory using the mkdir () function by passing in a directory name. However, the function rmdir () used to delete directories can only delete one empty directory and the directory must exist. If the directory is not empty, you need to enter the directory first, use the unlink () function to delete every file in the directory, and then go back to delete the empty directory. If there are still directories in the directory and the subdirectories are not empty, the recursive method should be used. The program code for custom recursive function to delete directory is as follows:

<?php
// Custom function recursively deletes the entire directory
function delDir($directory){
    if(file_exists($directory)){      // If it doesn't exist rmdir() Function will make an error
        if($dir_handle = @opendir($directory)){       // Open the directory and determine whether it was successfully opened
            while($filename = readdir($dir_handle)){       // Loop through all the files in the directory
               if($filename != "."&& $filename != ".."){       //1 Be sure to exclude two special directories
                   $subFile = $directory."/".$filename;       // Connect the subfiles in the directory with the current directory
                   if(is_dir($subFile))        // If it is a directory, the condition holds
                   delDir($subFile);       // Call its own function recursively and delete subdirectories
                   if(is_file($subFile))      // If it is a file, the condition holds
                   unlink($subFile);           // Delete this file directly
               }
            }
            closedir($dir_handle); // Close file resources
            rmdir($directory); // Delete an empty directory
         }
      }
}
 
dirDir("phpMyAdmin"); // Call delDir() Function, the "in the directory where the program is located" phpMyAdmin "File deletion
?>

Of course, you can also delete non-empty directories by calling the operating system command “rm-rf”, but try not to use them from the perspective of security and cross-platform.