Copy whole directory folder PHP
It is not exist any php function that allow make a copy of whole folder to another directory. The copy function not make it , only can a single file copy
below it show and explain some ways to do it.
function copyDirToDir($src,$dst){
$dir = opendir($src);
@mkdir($dst);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . DIRECTORY_SEPARATOR . $file) ) {
copyDirToDir($src . DIRECTORY_SEPARATOR . $file,$dst . DIRECTORY_SEPARATOR . $file);
}
else {
copy($src . DIRECTORY_SEPARATOR . $file,$dst . DIRECTORY_SEPARATOR . $file);
}
}
}
closedir($dir);
}
In this case the function copyDirToDir, receive as parameter a source direction and a destiny direction where it makes the copy
Pre-condition: 1- Both directories are valid , destiny direction is not need exist beacuse it will be create but the tree route until penultimate folder must be valid.
2- Must exist permissions in both directories for make copy and create files.
It makes a recursive search of the folders and copy all files.
Copy using command (shell_exec)
$src = "moises/home/public_html/folder";
$destiny = "moises/home/public_html/destiny ";shell_exec("cp -r $src $destiny");
Copy files by patterns
If we wants make a copy of all files with extensions (.php) in a folder, we can make use of the function copyPatternToDir see the way below:
function copyPatternToDir($pattern, $dir)
{
foreach (glob($pattern) as $file) {
if(!is_dir($file) && is_readable($file)) {
$dest = realpath($dir) .DIRECTORY_SEPARATOR. basename($file);
copy($file, $dest);
}
}
}
No hay comentarios:
Publicar un comentario