Home » Php » php – move all files in a folder to another?

php – move all files in a folder to another?

Posted by: admin April 23, 2020 Leave a comment

Questions:

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/*');
How to&Answers:

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

Answer:

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

Answer:

Please try this solution, it’s tested successfully ::

<?php
  $files = scandir("f1");
  $oldfolder = "f1/";
  $newfolder = "f2/";
  foreach($files as $fname) {
      if($fname != '.' && $fname != '..') {
          rename($oldfolder.$fname, $newfolder.$fname);
      }
  }
?>

Answer:

So I tried to use the rename() function as described and I kept getting the error back that there was no such file or directory. I placed the code within an if else statement in order to ensure that I really did have the directories created. It looked like this:

$tempDir = '/home/site/images/tmp/';
$permanentDir = '/home/site/images/' . $claimid; // this was stored above
mkdir($permanentDir,0775);
if(is_dir($permanentDir)){
    echo $permanentDir . ' is a directory';
    if(is_dir($tempDir)){
        echo $tempDir . ' is a directory';
    }else{
        echo $tempDir . ' is not a directory';
    }
}else{
    echo $permanentDir . ' is not a directory';
}

rename($tempDir . "*", $permanentDir);

So when I ran the code again, it spit out that both paths were directories. I was stumped. I talked with a coworker and he suggested, “Why not just rename the temp directory to the new directory, since you want to move all the files anyway?”

Turns out, this is what I ended up doing. I gave up trying to use the wildcard with the rename() function and instead just use the rename() to rename the temp directory to the permanent one.

so it looks like this.

$tempDir = '/home/site/images/tmp/';
$permanentDir = '/home/site/images/' . $claimid; // this was stored above
mkdir($permanentDir,0775);

rename($tempDir, $permanentDir);

This worked beautifully for my purposes since I don’t need the old tmp directory to remain there after the files have been uploaded and “moved”.

Hope this helps. If anyone knows why the wildcard doesn’t work in the rename() function and why I was getting the error stating above, please, let me know.

Answer:

tried this one?:

     <?php

     $oldfolderpath = "old/folder";
     $newfolderpath = "new/folder";

     rename($oldfolderpath,$newfolderpath);
     ?>

Answer:

Move or copy the way I use it

function copyfiles($source_folder, $target_folder, $move=false) {
    $source_folder=trim($source_folder, '/').'/';
    $target_folder=trim($target_folder, '/').'/';
    $files = scandir($source_folder);
    foreach($files as $file) {
        if($file != '.' && $file != '..') {
            if ($move) {
                rename($source_folder.$file, $target_folder.$file);
            } else {
                copy($source_folder.$file, $target_folder.$file);
            }
        }
    }   
}

function movefiles($source_folder, $target_folder) {
    copyfiles($source_folder, $target_folder, $move=true);
}

Answer:

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

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

Answer:

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

mkdir('newpath');
rename('path/*', 'newpath/');

Answer:

As a side note; when you copy files to another folder, their last changed time becomes current timestamp. So you should touch() the new files.

... (some codes for directory looping) ...
if (copy($source.$file, $destination.$file)) {
   $delete[] = $source.$file;

   $filetimestamp = filemtime($source.$file); 
   touch($destination.$file,$filetimestamp);
}
... (some codes) ...

Answer:

Not sure if this helps anyone or not, but thought I’d post anyway. Had a challenge where I has heaps of movies I’d purchased and downloaded through various online stores all stored in one folder, but all in their own subfolders and all with different naming conventions. I wanted to move all of them into the parent folder and rename them all to look pretty. all of the subfolders I’d managed to rename with a bulk renaming tool and conditional name formatting. the subfolders had other files in them i didn’t want. so i wrote the following php script to, 1. rename/move all files with extension mp4 to their parent directory while giving them the same name as their containing folder, 2. delete contents of subfolders and look for directories inside them to empty and then rmdir, 3. rmdir the subfolders.

$handle = opendir("D:/Movies/");
while ($file = readdir($handle)) {
if ($file != "." && $file != ".." && is_dir($file)) {
    $newhandle = opendir("D:/Movies/".$file);
    while($newfile = readdir($newhandle)) {
        if ($newfile != "." && $newfile != ".." && is_file("D:/Movies/".$file."/".$newfile)) {
            $parts = explode(".",$newfile);
            if (end($parts) == "mp4") {
                if (!file_exists("D:/Movies/".$file.".mp4")) {
                    rename("D:/Movies/".$file."/".$newfile,"D:/Movies/".$file.".mp4");
                }
                else {
                    unlink("D:/Movies/".$file."/".$newfile);
                }
            }
            else { unlink("D:/Movies/".$file."/".$newfile); }
        }
        else if ($newfile != "." && $newfile != ".." && is_dir("D:/Movies/".$file."/".$newfile)) {
            $dirhandle = opendir("D:/Movies/".$file."/".$newfile);
            while ($dirfile = readdir($dirhandle)){
                if ($dirfile != "." && $dirfile != ".."){
                    unlink("D:/Movies/".$file."/".$newfile."/".$dirfile);
                }
            }
            rmdir("D:/Movies/".$file."/".$newfile);
        }
    }
    unlink("D:/Movies/".$file);
}
}