简体   繁体   中英

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.

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

?>

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 (ie change ownership, etc.).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM