Unset item from Array $_FILES upload

对着背影说爱祢 提交于 2019-12-11 19:02:36

问题


I have a script where users can upload multiple files (max. 8). The HTML is generated by a piece of PHP:

$max_no_img=8;  
for($i=1; $i<=$max_no_img; $i++){
    <div class='photo photo$i'>
        <div class='new_label'>
        Foto $i:
        </div>
        <div class='new_input'>
        <input type='file' name='images[]' />
        </div>
    </div>";
}

So the array images[] consists of 8 values. However, every time a user submit it's form, the form is generating an Array of 8 items and by so, inserting 8 values in the database (whether they are empty or not).

So I would like to unset the empty values, copy the files to my folders and insert the link into my database. But here is the part where the errors happen.

The array of $_FILES consists of 4 things. name, tmp_name, error and size. How do I get it so a complete item (let's say images[0]) will be unset from the array so I can continue with the items which actually carry a value.

I tried this, but with no results...

unset($_FILES['images'][0])

and

unset($_FILES['images']['name'][0])
unset($_FILES['images']['tmp_name'][0])
unset($_FILES['images']['error'][0])
unset($_FILES['images']['size'][0])

Any advice how to unset a value from a $_FILES-arry?


回答1:


You can just ignore them instead of processing or unsetting any items:

if (!empty($_FILES['images'])) {
    for ($i = 0; $i < count($_FILES['images']['name']); $i++) {
        if (empty($_FILES['images']['name'][$i])) {
            // This item is empty
            echo "Item $i references an empty field.\n";
            continue;
        }

        echo "Item $i is a valid file.\n";
    }
}



回答2:


You do not actually need to unset any items. Simply skip over the items that don't correspond to an uploaded file:

for($i=1; $i <= $max_no_img; $i++) {
    if(empty($_FILES['images']['name'][$i])) {
        continue; // that's all it takes
    }
}


来源:https://stackoverflow.com/questions/8552390/unset-item-from-array-files-upload

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!