How can recursion be utilized to efficiently copy directories and files to another server in PHP?
To efficiently copy directories and files to another server in PHP, recursion can be utilized to traverse through the directory structure and copy each file and subdirectory. By recursively copying files and directories, we can ensure that the entire structure is replicated accurately on the destination server.
function copyDirectory($src, $dest) {
$dir = opendir($src);
@mkdir($dest);
while(false !== ($file = readdir($dir))) {
if (($file != '.') && ($file != '..')) {
if (is_dir($src . '/' . $file)) {
copyDirectory($src . '/' . $file, $dest . '/' . $file);
} else {
copy($src . '/' . $file, $dest . '/' . $file);
}
}
}
closedir($dir);
}
copyDirectory('/path/to/source/directory', '/path/to/destination/directory');
Keywords
Related Questions
- What are some best practices for efficiently reversing and reformatting array elements in PHP?
- How can PHP be used to display messages in a chat simulation from a database in random order?
- How can the PHP short-hand notation <?= be used and what are the potential pitfalls when short_open_tags are disabled?