Although copying a directory is the basic function of file operations. However, PHP also does not give a specific function, the same need to customize a recursive function implementation. To copy a directory that contains more than one subdirectory, it involves the copying of files, the creation of directories, and so on. Copying a file can be done through the copy () function provided by PHP, and the mkdir () function can be used to create the directory. When you define a function, you first iterate through the source directory, and if you encounter a normal file, copy it directly using the copy () function. If you encounter a directory while traversing, you must set up the directory and then copy the files in that directory, and if there are subdirectories, repeat the operation recursively, and the entire directory will eventually replicate. Custom recursive functions The program code for replicating directories is as follows:
Copy Code code as follows:
<?php
Replication of custom function recursively directories with multiple subdirectories
function Copydir ($DIRSRC, $dirTo) {
if (Is_file ($dirTo)) {//exit if the target is not a directory
echo "Target is not directory cannot be created!! ";
Return Exit function
}
if (!file_exists ($dirTo)) {//exit if the target is not a directory
mkdir ($dirTo); Create a table of contents
}
if ($dir _handle = @opendir ($directory)) {//Open directory and determine if it will open successfully
while ($filename = Readdir ($dir _handle)) {//Loop through all the files in the directory
if ($filename!= "." && $filename!= "...") {//Be sure to exclude two special directories
$subFile = $directory. " /". $filename; Connect the files in the directory to the current directory
$sunToFile = $dirTo. " /". $filename; Connecting multiple subdirectories of a target directory
if (Is_dir ($subSrcFile))//If the directory is the condition
Copydir ($subSrcFile, $subToFile); Recursively calls itself to replicate subdirectories
if (Is_file ($subSrcFile))//If the file is the condition
Copy ($subSrcFile, $subToFile); Copy directly to target location
}
}
Losedir ($dir _handle); To close a file resource
}
}
Test the function to copy the directory "phpMyAdmin" to "D:/admin"
Copydir ("phpMyAdmin", "d:/admin");
?>
From security and cross-platform considerations, try not to call the operating system's shell command "CP-A" to complete directory replication.