Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP copy all files in a directory to another?

Tags:

php

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.

like image 247
Panny Monium Avatar asked Dec 12 '22 10:12

Panny Monium


2 Answers

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

?>
like image 172
Panny Monium Avatar answered Dec 23 '22 06:12

Panny Monium


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.

like image 21
Mike Brant Avatar answered Dec 23 '22 06:12

Mike Brant