3

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

1
  • Hey look like i need to remove this statement is that correct? @mkdir( $target );
    – santosh
    Oct 3, 2009 at 12:30

8 Answers 8

3

Hello there little php developers this not a question but an answer to a question on how to copy files from one folder to another. I have come across over the internet that some developers use rename()instead of copy() to move files from one directory to another. Here is simple working code. Tested and work like charm.

<===========================The Magic============================>

<?php    
    $dir = "path/to/targetFiles/";
    $dirNew="path/to/newFilesFolder/";
    // Open a known directory, and proceed to read its contents
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {
            while (($file = readdir($dh)) !== false) {
            //exclude unwanted 
            if ($file==".") continue;
            if ($file=="..")continue;
            //if ($file=="index.php") continue; for example if you have index.php in the folder

            if (copy("$dir/$file","$dirNew/$file"))
                {
                echo "Files Copyed Successfully";
                //echo "<img src=$dirNew/$file  />"; 
                //if files you are moving are images you can print it from 
                //new folder to be sure they are there 
                }
                else {echo "File Not Copy";}
            }
            closedir($dh);
        }
    }


    ?>
1
  • thanx alot ... your answer save my day Jul 30, 2015 at 6:04
1
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.

1
<?php 
/** 
 * Copy a file, or recursively copy a folder and its contents 
 * 
 * @author      Aidan Lister <[email protected]> 
 * @version     1.0.1 
 * @param       string   $source    Source path 
 * @param       string   $dest      Destination path 
 * @return      bool     Returns TRUE on success, FALSE on failure 
 */ 
function copyr($source, $dest) 
{ 
    // Simple copy for a file 
    if (is_file($source)) {
        chmod($dest, 777);
        return copy($source, $dest); 
    } 

    // Make destination directory 
    if (!is_dir($dest)) { 
        mkdir($dest); 
    }

    chmod($dest, 777);

    // Loop through the folder 
    $dir = dir($source); 
    while (false !== $entry = $dir->read()) { 
        // Skip pointers 
        if ($entry == '.' || $entry == '..') { 
            continue; 
        } 

        // Deep copy directories 
        if ($dest !== "$source/$entry") { 
            copyr("$source/$entry", "$dest/$entry"); 
        } 
    } 

    // Clean up 
    $dir->close(); 
    return true; 
} 

?>
1
  • Why would you chmod 777?
    – Seer
    Oct 22, 2015 at 20:42
0

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.

0

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.

0

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

1
  • 1
    "hardlink farm" sounds interesting!
    – anon
    Jan 28, 2010 at 7:53
0

for windows server:

shell_exec('xcopy \\old\\folder \\new\\folder /s /e /y /i');

for linux server:

shell_exec('cp -R /old/folder /new/folder');
0

I have tried all the examples but no one is copying sub folders and its data. Finally I got the answer:

<?php

    $dir = "/var/www/html/json/";
    $dirNew = "/var/www/html/json1/";
    // Open a known directory, and proceed to read its contents
    recurse_copy($dir, $dirNew);
    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);
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.