2012-03-23 5 views
8

Я хочу переместить все файлы и папки внутри папки в другую папку. Я нашел код для копирования всех файлов внутри папки в другую папку. move all files in a folder to anotherперемещать все файлы и папки в папку в другую?

// Get array of all source files 
$files = scandir("source"); 
// Identify directories 
$source = "source/"; 
$destination = "destination/"; 
// Cycle through all source files 
foreach ($files as $file) { 
    if (in_array($file, array(".",".."))) continue; 
    // If we copied this successfully, mark it for deletion 
    if (copy($source.$file, $destination.$file)) { 
    $delete[] = $source.$file; 
    } 
} 
// Delete all successfully-copied files 
foreach ($delete as $file) { 
    unlink($file); 
} 

Как изменить это, чтобы переместить все папки и файлы внутри этой папки в другую папку.

+0

возможный дубликат [Скопировать все файлы и папки из одного каталога в другой каталог PHP] (Http: // StackOverflow. com/questions/1513618/copy-all-files-and-folder-from-one-directory-to-another-directory-php) –

ответ

22

Это то, что я использую

// Function to remove folders and files 
    function rrmdir($dir) { 
     if (is_dir($dir)) { 
      $files = scandir($dir); 
      foreach ($files as $file) 
       if ($file != "." && $file != "..") rrmdir("$dir/$file"); 
      rmdir($dir); 
     } 
     else if (file_exists($dir)) unlink($dir); 
    } 

    // Function to Copy folders and files  
    function rcopy($src, $dst) { 
     if (file_exists ($dst)) 
      rrmdir ($dst); 
     if (is_dir ($src)) { 
      mkdir ($dst); 
      $files = scandir ($src); 
      foreach ($files as $file) 
       if ($file != "." && $file != "..") 
        rcopy ("$src/$file", "$dst/$file"); 
     } else if (file_exists ($src)) 
      copy ($src, $dst); 
    } 

Использование

rcopy($source , $destination); 

Другой пример без удаления файла назначения или папку

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

Пожалуйста, см: http://php.net/manual/en/function.copy.php для более сочных примеров

Благодаря :)

+7

+1 для правильного использования слова 'juicy' –

+5

Это действительно не самый лучший вариант! Используйте [rename ($ sourceFolder, $ targetFolder)] (http://www.php.net/manual/de/function.rename.php), а это всего лишь одна строка кода и перемещает вашу полную папку. Я знаю, что имя метода не дает понять, что он действительно перемещает вещи вокруг, но это хорошо. – vinzenzweber

+0

Я знаю, что это старый пост, но все же - вам не нужно использовать DIRECTORY_SEPARATOR вместо '/' для обеспечения совместимости системы? –

15

Использовать rename вместо copy.

В отличие от функции C с тем же именем, rename может перемещать файл из одной файловой системы в другую (начиная с PHP 4.3.3 в Unix и начиная с PHP 5.3.1 в Windows).

+0

Спасибо, что дали свое драгоценное время, чтобы ответить на проблему ... но я уверен, что это не имеет отношения к проблеме. Ваш ответ работает только для ** файлы ** и не для папки. –

0

Я использую его

// function used to copy full directory structure from source to target 
function full_copy($source, $target) 
{ 
    if (is_dir($source)) 
    { 
     mkdir($target, 0777); 
     $d = dir($source); 

     while (FALSE !== ($entry = $d->read())) 
     { 
      if ($entry == '.' || $entry == '..') 
      { 
       continue; 
      } 

      $Entry = $source . '/' . $entry;   
      if (is_dir($Entry)) 
      { 
       full_copy($Entry, $target . '/' . $entry); 
       continue; 
      } 
      copy($Entry, $target . '/' . $entry); 
     } 

     $d->close(); 

    } else { 
     copy($source, $target); 
    } 
} 
7

перемещения папки:

rename("./path/old_folder_name", "./path/new_folder_name"); 
0
$src = 'user_data/company_2/T1/'; 
$dst = 'user_data/company_2/T2/T1/'; 

rcopy($src, $dst); // Call function 
// Function to Copy folders and files  
function rcopy($src, $dst) { 
    if (file_exists ($dst)) 
     rrmdir ($dst); 
    if (is_dir ($src)) { 
     mkdir ($dst); 
     $files = scandir ($src); 
     foreach ($files as $file) 
      if ($file != "." && $file != "..") 
       rcopy ("$src/$file", "$dst/$file"); 

    } else if (file_exists ($src)) 
     copy ($src, $dst); 
        rrmdir ($src); 
}  

// Function to remove folders and files 
function rrmdir($dir) { 
    if (is_dir($dir)) { 
     $files = scandir($dir); 
     foreach ($files as $file) 
      if ($file != "." && $file != "..") rrmdir("$dir/$file"); 
     rmdir($dir); 
    } 
    else if (file_exists($dir)) unlink($dir); 
} 
Смежные вопросы