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 (i.e. change ownership, etc.).
This should also execute much faster than your file-by-file recursive approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With