Dave Lynch Dave Lynch - 8 days ago 5
PHP Question

php copy file for each filename in array

I am trying to move all the files in my array from one directory to another.

I have done some research and are using the php Copy() function.
here is my code so far:

$filenameArray = "img1.png,img2.png,img3.png";

$sourcePath = "/source/";
$savePath = "/newDir/";

$myArray = explode(',', $filenameArray);
$finalArray = print_r($myArray);

function copyFiles($finalArray,$sourcePath,$savePath) {
for($i = 0;$i < count($finalArray);$i++){
copy($sourcePath.$finalArray[$i],$savePath.$finalArray[$i]);}
}


Anyone see where I'm going wrong?

Thanks in advance!

Answer

In your code you are not calling the copyFile function. Try this:

$filenameArray = "img1.png,img2.png,img3.png";

$sourcePath = "/source/";
$savePath = "/newDir/";

$finalArray = explode(',', $filenameArray);

function copyFiles($finalArray,$sourcePath,$savePath) {
   foreach ($finalArray as $file){
     if (!copy($sourcePath.$file,$savePath.$file)) {
         echo "failed to copy $file...\n";
     }
   }
}

copyFiles( $finalArray, $sourcePath, $savePath);