tags:

views:

77

answers:

4

when moving one file from one location to another i use

rename('path/filename', newpath/filename');

how do you move all files in a folder to another folder? tried this one without result:

rename('path/*', 'newpath/*');
+1  A: 

A slightly verbose solution:

    // 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);
    }
Jonathan Sampson
i have files in the destination folder and i want to keep them. just move the files from a temporary folder to that folder so you ADD files all the time.
weng
i dont get the line: if (in_array($file, array(".",".."))) continue; what is it doing?
weng
Noname, two of the items in this array will be "." representing "current" directory, and ".." representing "previous" directory. When we come across these, we just "continue," meaning we skip the current iteration.
Jonathan Sampson
it was a great function that worked except if there were directories in the source folder. is there a way to circumvent this? and arent there libraries with classes for these operations? zend framework?
weng
A: 

try this: rename('path/*', 'newpath/');

I do not see a point in having an asterisk in the destination

Aadith
didnt work.."No such file or directory"
weng
A: 

If the target directory doesn't exist, you'll need to create it first:

mkdir('newpath');
rename('path/*', 'newpath/');
adam
+1  A: 

An alternate using rename() and with some error checking:

$srcDir = 'dir1';
$destDir = 'dir2';

if (file_exists($destDir)) {
  if (is_dir($destDir)) {
    if (is_writable($destDir)) {
      if ($handle = opendir($srcDir)) {
        while (false !== ($file = readdir($handle))) {
          if (is_file($srcDir . '/' . $file)) {
            rename($srcDir . '/' . $file, $destDir . '/' . $file);
          }
        }
        closedir($handle);
      } else {
        echo "$srcDir could not be opened.\n";
      }
    } else {
      echo "$destDir is not writable!\n";
    }
  } else {
    echo "$destDir is not a directory!\n";
  }
} else {
  echo "$destDir does not exist\n";
}
GreenMatt