沃梦达 / 编程问答 / php问题 / 正文

目录的递归复制

Recursive Copy of Directory(目录的递归复制)

本文介绍了目录的递归复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的旧 VPS 上,我使用以下代码将目录中的文件和目录复制到用户提交表单后创建的新目录中.

On my old VPS I was using the following code to copy the files and directories within a directory to a new directory that was created after the user submitted their form.

function copyr($source, $dest)
{
   // Simple copy for a file
   if (is_file($source)) {
      return copy($source, $dest);
   }

   // Make destination directory
   if (!is_dir($dest)) {
      mkdir($dest);
      $company = ($_POST['company']);
   }

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

copyr('Template/MemberPages', "Members/$company")

但是现在在我的新 VPS 上,它只会创建主目录,而不会将任何文件复制到其中.我不明白这两个 VPS 之间会发生什么变化?

However now on my new VPS it will only create the main directory, but will not copy any of the files to it. I don't understand what could have changed between the 2 VPS's?

推荐答案

试试这个:

$source = "dir/dir/dir";
$dest= "dest/dir";

mkdir($dest, 0755);
foreach (
 $iterator = new RecursiveIteratorIterator(
  new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
  RecursiveIteratorIterator::SELF_FIRST) as $item
) {
  if ($item->isDir()) {
    mkdir($dest . DIRECTORY_SEPARATOR . $iterator->getSubPathname());
  } else {
    copy($item, $dest . DIRECTORY_SEPARATOR . $iterator->getSubPathname());
  }
}

迭代器遍历所有文件夹和子文件夹,并将文件从 $source 复制到 $dest

Iterator iterate through all folders and subfolders and make copy of files from $source to $dest

这篇关于目录的递归复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:目录的递归复制

基础教程推荐