0

I have used the following code several times before, and have recently found it to try and use again. There now seems to be an error which I cannot fix, can anyone see what I am doing wrong?

foreach ($_FILES['image']['name'] as $i => $name) {     

    $uploadfile = $uploaddir . basename($name);

    if (!move_uploaded_file($file_post["tmp_name"][$i],$uploadfile)) 
    {
        echo set_e('error','Image ['.$i.'] not uploaded','');
    }


}

The error I get is

Warning: Invalid argument supplied for foreach() in /sitefolder/functions.php on line 1096

line 1096 is the first line in the first code box

1 Answer 1

3

First, never use array keys without checking that they exist. Wrap you code in

if (array_key_exists('image', $_FILES)) 
{
  // ...
} 
else 
{
  // error handling
}

Second, even if the key exists, $_FILES['image']['name'] is supposed to be a string, you cannot feed this to foreach anyway. Better:

foreach ($_FILES as $file) 
{     
  $uploadfile = $uploaddir . basename($file['name']);
  if (!move_uploaded_file($file["tmp_name"], $uploadfile)) 
  {
      echo set_e('error','Image ['.$i.'] not uploaded','');
  }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Hi tried original code, and tried it with the edit i added and it still doesnt work
@Ben: Can you explain what "doesn't work" means? A print_r() of $_FILES might also give some insight.
I mean it display the error message set_e(...). Also the print_r is returning empty ... Array()
Did you have the enctype="multipart/form-data" on the <form> tag?
I added it in after seeing the array was empty. Also change the form input elements from being an array. They're uploading now, just having to mess with the code moving it from the tmp folder. Thanks for the help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.