laurens
laurens

Reputation: 497

Copy folder without overwriting

I found this question (here) about copying a file without overwriting

How do you copy a file in PHP without overwriting an existing file?

What I need is a php script to copy all files in a folder, there are also some subfolders; so it should be recursive.

I need to transfer it via FTP so I don't know this makes a big difference to the approach.

Thanks a lot in advance!

Upvotes: 1

Views: 1070

Answers (2)

user207675
user207675

Reputation: 74

There is a big difference between filesystem copy and FTP copy you could take a look at the PEAR FTP Class

Upvotes: 0

Dominic Rodger
Dominic Rodger

Reputation: 99801

Try this, from a comment on the manual page for copy:

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

Note that this solution will happily overwrite any files that exist in the $dst directory. If you want to avoid that, you could wrap the code in this question into a function, and call that function instead of copy.

I'm not sure what you want to transfer via FTP, if you clarify that I'll be happy to edit my answer.

Upvotes: 3

Related Questions