Ben
Ben

Reputation: 702

multiple file upload foreach error

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

Upvotes: 0

Views: 2986

Answers (1)

Tomalak
Tomalak

Reputation: 338128

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

Upvotes: 3

Related Questions