I need to copy a route to another route, taking into account all files and directories in the first route, similar to the xcopy
I only know the function copy
, is there a function in PHP
that does it recursively?
I need to copy a route to another route, taking into account all files and directories in the first route, similar to the xcopy
I only know the function copy
, is there a function in PHP
that does it recursively?
In the PHP
documentation they propose the following recursive function using copy () to move directories , you can try it to see if it works.
<?php
function recurse_copy($src,$dst) {
$dir = opendir($src);
@mkdir($dst);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
recurse_copy($src . '/' . $file,$dst . '/' . $file);
}
else {
copy($src . '/' . $file,$dst . '/' . $file);
}
}
}
closedir($dir);
}
?>
With the response of @Juan Pinzón I have modified the function so that it takes into account if the resource should be overwritten if there is a resource with the same name in the destination.
function xcopy($src,$dst,$rwrite=false) {
$dir = opendir($src);
if (!file_exists($dst)) mkdir($dst);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
xcopy($src . '/' . $file,$dst . '/' . $file,$rwrite);
}
else {
if ($rwrite) copy($src . '/' . $file,$dst . '/' . $file);
}
}
}
closedir($dir);
}
By default it will not overwrite the resources, to allow overwriting of the resource use xcopy('origen','destino',true);