Reputation: 1031
I have form where I have three inputs for files. With code below, I try to move files from TMP localisation to ./uploads with some random hash and name of file.
I have issue with foreach
because it is stopping, after first iteration and saving file to uploads directory. I do not know why it is not happening for other two elements in table. Whole function below, it is a little mess, but I hope it is understandable.
function saveFile(){
global $patchFile;
$fileArray = [ $_FILES['file_one']['name'], $_FILES['file_two']['name'], $_FILES['file_three']['name'] ];
$tmpArray = [ $_FILES['file_one']['tmp_name'], $_FILES['file_two']['tmp_name'], $_FILES['file_three']['tmp_name'] ];
$multiArray =
[
[$_FILES['file_one']['name'], $_FILES['file_one']['tmp_name']],
[$_FILES['file_two']['name'], $_FILES['file_two']['tmp_name']],
[$_FILES['file_three']['name'], $_FILES['file_three']['tmp_name']]
];
foreach ($multiArray as $key)
{
echo "<br />Key: ".$key[0]."\n";
echo "Key_tmp: ".$key[1]."\n";
$randomString = generateRandomString();
$patchFile = './uploads/'.$randomString.$key[0];
echo "<br />Check patchFile: $patchFile";
if(is_uploaded_file($key[1]))
{
echo "<br />Begin uploading to directory...<br />";
if(!move_uploaded_file($key[1], $patchFile))
{
echo 'Problem: Nie udało się skopiować pliku do katalogu.';
return false;
}
else {
echo "File was saved in uploads directory";
return true;
}
}
else
{
echo "Uploading to directory... FAILED!";
}
}
}
Upvotes: 0
Views: 295
Reputation: 14230
When you return
something from a loop, the loop is always broken.
As per PHP manual:
If called from within a function, the
return
statement immediately ends execution of the current function, and returns its argument as the value of the function call.
Upvotes: 2