tags:

views:

326

answers:

4

Hello,

I tried to copy the entire contents of the directory to another location using

copy ("old_location/*.*","new_location/");

but it says it cannot find stream, true *.* is not found.

Any other way

Thanks Dave

+4  A: 

It seems that copy only handle single files. Here is a function for copying recursively I found on the copy documentation page:

<?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); 
} 
?>
Felix Kling
It's an asterisk and not a star ;)
Gordon
Uups :-) But I had to edit anyway ;)
Felix Kling
A: 

Rich Rodecker has a script on his blog that appears to do just that.

http://www.visible-form.com/blog/copy-directory-in-php/

jonfhancock
+3  A: 

copy() only works with files.

Both the DOS copy and Unix cp commands will copy recursively - so the quickest solution is just to shell out and use these. e.g.

`cp -r $src $dest`;

Otherwise you'll need to use the openddir/eraddir or scandir to read the contents of the directory, iterate through the results and if is_dir returns true for each one, recurse into it.

e.g.

function xcopy($src,$dest)
{
 foreach  (scandir($src) as $file) {
   if (!is_readable($src.'/'.$file)) continue;
   if (is_dir($file) && ($file!='.') && ($file!='..') ) {
       mkdir($dest . '/' . $file);
       xcopy($src.'/'.$file, $dest.'/'.$file);
   } else {
       copy($src.'/'.$file, $dest.'/'.$file);
   }
 }

C.

symcbean
A: 

Like said elsewhere, copy only works with a single file for source and not a pattern. If you want to copy by pattern, use glob to determine the files, then run copy. This will not copy subdirectories though, nor will it create the destination directory.

function copyToDir($pattern, $dir)
{
    foreach (glob($pattern) as $file) {
        if(!is_dir($file) && is_readable($file)) {
            $dest = realpath($dir . DIRECTORY_SEPARATOR) . basename($file);
            copy($file, $dest);
        }
    }    
}
copyToDir('./test/foo/*.txt', './test/bar'); // copies all txt files
Gordon