Copy all files and directories to a destination in Php

2

I need to copy a route to another route, taking into account all files and directories in the first route, similar to the xcopy

command

I only know the function copy , is there a function in PHP that does it recursively?

    
asked by Webserveis 08.06.2016 в 15:59
source

2 answers

4

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); 
} 
?>
    
answered by 08.06.2016 / 16:35
source
1

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);

    
answered by 08.06.2016 в 17:18