How do you loop through $_FILES array?

2019-01-06 15:27发布

Here are the inputs I want to loop through

Main photo:   <input type="file" name="image[]" />
Side photo 1: <input type="file" name="image[]" />
Side photo 2: <input type="file" name="image[]" />
Side photo 3: <input type="file" name="image[]" />

A couple weird things happened, when I uploaded nothing I use the count($_FILES['image']), I echoed that function, and it returns a value of 5. There should be no elements in that array. Why is there one extra input when I only have 4 files to begin with?

Now with the actually looping itself, I try using the foreach loop, but it doesn't work.

foreach($_FILES['image'] as $files){echo $files['name']; }

Nothing came up, what I wanted to ultimately do is to loop through all images, make sure they are correct format, size, and rename each of them. But this simple foreach() loop shows that somehow I can't even loop through the $_FILES array and the count() confused me even more when it say that there are 5 elements in the array when I didn't even upload anything.

7条回答
forever°为你锁心
2楼-- · 2019-01-06 16:31

just rename your fields this way

Main photo:   <input type="file" name="image1" />
Side photo 1: <input type="file" name="image2" />
Side photo 2: <input type="file" name="image3" />
Side photo 3: <input type="file" name="image4" />

and then you'll be able to iterate it usual way:

foreach($_FILES as $file){
  echo $file['name']; 
}
查看更多
登录 后发表回答