PHP Recursive Replication Mobile Directory Custom Function Sharing

  • 2021-08-03 09:36:58
  • OfStack

Although copying 1 directory is the basic function of file operation. However, PHP does not give a specific function, and it is also necessary to customize a recursive function implementation. To copy a directory with multiple subdirectories, file copying, directory creation, and so on will be involved. Copying a file can be done through the copy () function provided by PHP, and creating a directory can be done using the mkdir () function. When defining a function, first traverse the source directory, and if you encounter a normal file, use the copy () function to copy it directly. If one directory is encountered during the iteration, the directory must be established, and then the files under the directory must be copied. If there are subdirectories, the recursive repeated operation is used, and the whole directory must be copied finally. The program code for the custom recursive function to copy the directory is as follows:


<?php
// Custom functions recursively copy directories with multiple subdirectories
function copyDir($dirSrc,$dirTo){
    if(is_file($dirTo)){      // If the target is not 1 A directory exits
        echo " The target is not a directory cannot be created! ! ";
        return; // Exit function
    }
    if(!file_exists($dirTo)){       // If the target is not 1 A directory exits
       mkdir($dirTo);              // Create Directory
    }
 
    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
               $sunToFile = $dirTo."/".$filename;          // Connect multi-level subdirectories of the target directory
               if(is_dir($subSrcFile))          // If it is a directory, the condition holds
                   copyDir($subSrcFile,$subToFile);          // Recursively call yourself to copy subdirectories
               if(is_file($subSrcFile))          // If it is a file, the condition holds
                   copy($subSrcFile,$subToFile);          // Copy directly to the destination location
            }
        }
        losedir($dir_handle);          // Close file resources
     }
}
 
// Test the function and put the directory " phpMyAdmin "Copy to" D:/admin "
copyDir("phpMyAdmin","D:/admin");
?>

Considering security and cross-platform, try not to call the SHELL command "cp-a" of the operating system to complete directory replication.


Related articles: