Search code examples
phpcopymkdiropendirreaddir

PHP: Copy entire contents of a directory


Sorry for new post! I'm not yet trusted to comment on others posts.

I'm having trouble copying folders and this is where I started: Copy entire contents of a directory

Function

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

My input

$src = "http://$_SERVER[HTTP_HOST]/_template/function/";
$dst = "http://$_SERVER[HTTP_HOST]/city/department/function/";
recurse_copy($src, $dst);

I've also tried this

$src = "$_SERVER[DOCUMENT_ROOT]/_template/function/"; // And so on...

The function is executed but nothing is being copied.

Any ideas on what might be wrong?

SOLVED

Working solution

Along with

$src = "$_SERVER[DOCUMENT_ROOT]/_template/function/";
$dst = "$_SERVER[DOCUMENT_ROOT]/city/department/function/";
recurse_copy($src, $dst);

Solution

  • It's not tested but I think the issue might be that the target directory is not necessarily being created before attempting to copy files to it. The piece of code that creates the target directory would require a folder path rather than a full filepath - hence using dirname( $dst )

    if( !defined('DS') ) define( 'DS', DIRECTORY_SEPARATOR );
    
    function recurse_copy( $src, $dst ) { 
    
        $dir = opendir( $src ); 
        @mkdir( dirname( $dst ) );
    
        while( false !== ( $file = readdir( $dir ) ) ) { 
            if( $file != '.' && $file != '..' ) { 
                if( is_dir( $src . DS . $file ) ) { 
                    recurse_copy( $src . DS . $file, $dst . DS . $file ); 
                } else { 
                    copy( $src . DS . $file, $dst . DS . $file ); 
                } 
            } 
        } 
        closedir( $dir ); 
    }