Panny Monium
Panny Monium

Reputation: 301

PHP copy all files in a directory to another?

I am trying to copy files to from a specific folder ($src) to a specific destination ($dst). I obtained the code from this tutorial here. I can't seem to manage to copy any files within the source directory.

<?php


$src = 'pictures';
$dst = 'dest';

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

?>

I am not getting any errors for the above code.

Upvotes: 6

Views: 30171

Answers (2)

Panny Monium
Panny Monium

Reputation: 301

I just tried this and it worked for me like a charm.

<?php

$src = 'pictures';
$dst = 'dest';
$files = glob("pictures/*.*");
      foreach($files as $file){
      $file_to_go = str_replace($src,$dst,$file);
      copy($file, $file_to_go);
      }

?>

Upvotes: 11

Mike Brant
Mike Brant

Reputation: 71422

I would just use shell command to do this if you don't have any special treatment you are trying to do (like filtering certain files or whatever).

An example for linux:

$src = '/full/path/to/src'; // or relative path if so desired 
$dst = '/full/path/to/dst'; // or relative path if so desired
$command = 'cp -a ' . $src . ' ' .$dst;
$shell_result_output = shell_exec(escapeshellcmd($command));

Of course you would just use whatever options are available to you from shell command if you want to tweak the behavior (i.e. change ownership, etc.).

This should also execute much faster than your file-by-file recursive approach.

Upvotes: 3

Related Questions