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

时间:2022-03-14 06:25:11

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.

我有名为“mysourcedir”的目录,它有sonme文件和文件夹。所以我想使用PHP将此目录中的所有内容复制到Linux服务器上的其他“目标文件夹”。

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

我正在尝试此代码,但它确实存在一些问题,它在目标位置创建目录“mysourcedir”。我希望只复制目的地的所有文件和文件夹。请建议

8 个解决方案

#1


2  

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.

你好,小php开发人员这不是一个问题,而是一个关于如何将文件从一个文件夹复制到另一个文件夹的问题的答案。我通过互联网遇到一些开发人员使用rename()而不是copy()将文件从一个目录移动到另一个目录。这是简单的工作代码。经过测试和工作就像魅力。

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


    ?>

#2


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

FolderCopy :: copyFolder(dirname(dirname(FILE))。“/ images”,dirname(FILE)。“/ test”);

This is my suggestion.

这是我的建议。

#3


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

?>

#4


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.

虽然我个人会避免使用同名的2个变量而只使用captilisation来区分它们。查看http://www.php.net/copy上的用户评论以了解其他可能性。

#5


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.

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

#6


0  

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

尝试运行cp -a。这需要保留mod时间和权限,以及所有这些。 cp -al将成为一个硬链接农场。

#7


0  

for windows server:

对于Windows服务器:

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

for linux server:

对于linux服务器:

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

#8


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

#1


2  

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.

你好,小php开发人员这不是一个问题,而是一个关于如何将文件从一个文件夹复制到另一个文件夹的问题的答案。我通过互联网遇到一些开发人员使用rename()而不是copy()将文件从一个目录移动到另一个目录。这是简单的工作代码。经过测试和工作就像魅力。

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


    ?>

#2


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

FolderCopy :: copyFolder(dirname(dirname(FILE))。“/ images”,dirname(FILE)。“/ test”);

This is my suggestion.

这是我的建议。

#3


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

?>

#4


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.

虽然我个人会避免使用同名的2个变量而只使用captilisation来区分它们。查看http://www.php.net/copy上的用户评论以了解其他可能性。

#5


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.

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

#6


0  

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

尝试运行cp -a。这需要保留mod时间和权限,以及所有这些。 cp -al将成为一个硬链接农场。

#7


0  

for windows server:

对于Windows服务器:

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

for linux server:

对于linux服务器:

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

#8


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