tags:

views:

714

answers:

4

Hi,

I have directory called "mysourcedir" it has sonme files and folders. so i want to copy all content from this directory to some other "destinationfolder" on Linux server using PHP.

function full_copy( $source, $target ) {
if ( is_dir( $source ) ) {
 @mkdir( $target );
 $d = dir( $source );
 while ( FALSE !== ( $entry = $d->read() ) ) {
  if ( $entry == '.' || $entry == '..' ) {
   continue;
  }
  $Entry = $source . '/' . $entry; 
  if ( is_dir( $Entry ) ) {
   $this->full_copy( $Entry, $target . '/' . $entry );
   continue;
  }
  copy( $Entry, $target . '/' . $entry );
 }

 $d->close();
}else {
 copy( $source, $target );
}

}

I am trying this code, but it does some problem, it creates directory "mysourcedir" at destination location. I am expecting to just copy all files and folders at destination,. Please suggest

A: 

You probably just want to move that line down, like this:

function full_copy( $source, $target ) {
if ( is_dir( $source ) ) {
        $d = dir( $source );
        while ( FALSE !== ( $entry = $d->read() ) ) {
                if ( $entry == '.' || $entry == '..' ) {
                        continue;
                }
                $Entry = $source . '/' . $entry; 
                if ( is_dir( $Entry ) ) {
                        @mkdir( $Entry );
                        $this->full_copy( $Entry, $target . '/' . $entry );
                        continue;
                }
                copy( $Entry, $target . '/' . $entry );
        }

        $d->close();
}else {
        copy( $source, $target );
}

Although personally I would avoid using 2 variables with the same name with only captilisation to differentiate them. Check the user comments on http://www.php.net/copy for other possibilities.

Russ
A: 
class FolderCopy {


  public static function copyFolder($src, $dest) {

    $path = realpath($src);
    $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);

      /** SplFileInfo $object*/
    foreach($objects as $name => $object)
    {
      $startsAt = substr(dirname($name), strlen($src));
      self::mkDir($dest.$startsAt);
      if(is_writable($dest.$startsAt) and $object->isFile())
      {
          copy((string)$name, $dest.$startsAt.DIRECTORY_SEPARATOR.basename($name));
      }
    }
  }

  private static function mkDir($folder, $perm=0777) {
    if(!is_dir($folder)) {
      mkdir($folder, $perm);
    }
  }

}

FolderCopy::copyFolder(dirname(dirname(FILE))."/images", dirname(FILE)."/test");

This is my suggestion.

Tom Schaefer
A: 

I think taht the $d->read() will return also the name of the parent and hat is why you are creating it again in the target directory.

Teo
A: 

try running cp -a. That takes care of preserving mod times and permissions, and all that. cp -al will make a hardlink farm.

Peter Cordes
"hardlink farm" sounds interesting!