dev_huesca
dev_huesca

Reputation: 516

copy file to every dir and subdir in path PHP

I need a script to copy a file to every dir and subdir inside a specific folder.

Inside a folder called 'projects' i have several folders with several folders inside them (and so on), i need a script that checks if there is a specific file in that folder, if exist, then do nothing, if not, copy it.

I need to do this in php...

Can you help?

Upvotes: 1

Views: 454

Answers (2)

Afshin
Afshin

Reputation: 4215

i hope this code can help you for what you want

$maindir=".";
mylistFolderFiles($maindir);
function mylistFolderFiles($dir){
  $file = 'example.txt';
  $ffs = scandir($dir);
  foreach($ffs as $ff){
    if($ff != '.' && $ff != '..'){
        if(is_dir($dir.'/'.$ff)) {
            $newfile=$dir.'/'.$ff .'/'. $file ;
            if (!copy($file, $newfile)) {
                echo "failed to copy $file...\n";
            }
            mylistFolderFiles($dir.'/'.$ff);
      } 
    }

  }

}

Upvotes: 1

Baba
Baba

Reputation: 95131

This would copy all files , all folders and its content .... from cunnrent directory to target .. using RecursiveDirectoryIterator and RecursiveIteratorIterator

echo "<pre>";
mkdirRecursive($target);
if (! is_writable($target)) {
    echo "You don't have permission wo write to ", $target, PHP_EOL;
}
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
while ( $it->valid() ) {
    if (! $it->isDot()) {
        $name = $it->key();
        $final = $target . str_replace($dir, "", $name);
        if (! mkdirRecursive(dirname($final))) {
            echo "Can Create Directory : ", dirname($final), PHP_EOL;
            continue;
        }
        if (! @copy($name, $final)) {
            echo "Can't Copy : ", dirname($final), PHP_EOL;
            continue;
        }
        echo "Copied ", basename($name), " to ", dirname($final), PHP_EOL;
    }
    $it->next();
}

function mkdirRecursive($pathname, $mode = 0777) {
    is_dir(dirname($pathname)) || mkdirRecursive(dirname($pathname), $mode);
    return is_dir($pathname) || @mkdir($pathname, $mode);
}

Upvotes: 1

Related Questions