多文件上传foreach错误

时间:2011-11-18 18:16:23

标签: php file upload

之前我曾多次使用过以下代码,并且最近发现它再次尝试使用。现在似乎有一个我无法修复的错误,任何人都可以看到我做错了吗?

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


}

我得到的错误是

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

第1096行是第一个代码框中的第一行

1 个答案:

答案 0 :(得分:3)

首先,永远不要使用数组键而不检查它们是否存在。包裹你的代码

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

其次,即使密钥存在,$_FILES['image']['name']应该是一个字符串,但无论如何都不能将其提供给foreach。更好:

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