6

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.

Community
  • 1
  • 1
Panny Monium
  • 301
  • 2
  • 4
  • 20
  • Are you able to read the files? are you getting any error? – Ricardo Nuñez Oct 02 '13 at 23:28
  • 1
    I like how so many post a question while leaving out the most important part, the error message... – OIS Oct 02 '13 at 23:29
  • Is using a linux shell command out of the question for some reason? It doesn't seem like you are doing anything particularly interesting here (like filtering out certain files), so I would just use linux command (called from PHP if necessary). – Mike Brant Oct 02 '13 at 23:29
  • I'm not getting any errors for the above code – Panny Monium Oct 02 '13 at 23:31
  • I compared your function with the one you referenced, and it seems valid. One of the candidates for "No result, no error" situation: of course, you did run``recurse_copy($src,$dst);`` in your code? – Kita Oct 03 '13 at 00:30

2 Answers2

11

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

?>
Panny Monium
  • 301
  • 2
  • 4
  • 20
3

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.

Mike Brant
  • 70,514
  • 10
  • 99
  • 103
  • Preferred approach for (1) performance: as you mentioned this will "execute much faster than your file-by-file recursive approach"; and (2) delegation of concerns: you should use the file system to deal with the file system, and php to deal with the web. – Nick Mitchell Oct 01 '14 at 20:46