将一个目录中的所有文件和文件夹复制到另一个目录中 PHP

3

我有一个名为“mysourcedir”的目录,里面包含一些文件和文件夹。因此,我希望使用PHP将该目录中的所有内容复制到Linux服务器上的其他“destinationfolder”中。

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

我正在尝试这段代码,但出现了一些问题,它会在目标位置创建一个名为“mysourcedir”的目录。我希望只是将所有文件和文件夹复制到目标位置,请给予建议。


嘿,看起来我需要删除这个语句,是吗? @mkdir($target); - santosh
8个回答

3

大家好,这篇文章不是问题,而是回答如何将文件从一个文件夹复制到另一个文件夹的问题。我在网上发现一些开发人员使用rename()而不是copy()来移动文件。

以下是简单的可行代码,经过测试可以完美运行。

<===========================神奇的分割线============================>

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


    ?>

非常感谢,你的回答救了我的一天。 - deemi-D-nadeem

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

这是我的建议。


1
<?php 
/** 
 * Copy a file, or recursively copy a folder and its contents 
 * 
 * @author      Aidan Lister <aidan@php.net> 
 * @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; 
} 

?>

为什么要使用chmod 777? - Seer

0

我尝试了所有的例子,但没有一个能够复制子文件夹及其数据。最终我找到了答案:

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

0

你可能只是想把那行代码往下移,像这样:

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

虽然个人认为最好避免使用只有大小写区分的相同变量名。请查看http://www.php.net/copy上的用户评论以获取其他可能性。


0

尝试运行 cp -a 命令。这将确保保留修改时间和权限等所有内容。cp -al 将创建一个硬链接集合。


1
“硬链接农场”听起来很有趣! - anon

0

我认为 $d->read() 也会返回父级名称,这就是你在目标目录中再次创建它的原因。


0

适用于 Windows 服务器:

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

对于Linux服务器:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接