开发者

Why form posting yields $_FILES['thefile']['name'][0] instead of $_FILES['thefile'][0]['name']?

When you name several file input fields with the same name and an array index like so:

<input type='file' name='thefile[0]'>

<input type='file' name='thefile[1]'>

Then in the form submission you get this:

$_FILES['thefile']['name'][0]

$_FILES['thefile']['name'][1]

And开发者_如何学Go so on with the other fields.

I find this annoying because it prevents reusing the code for non-array file uploads.

Wouldn't this be better:?

$_FILES['thefile'][0]['name'] and so on?

Does someone know the reason behind this strange CGI/HTML implementation?


It was an unfortunate design decision and its too late to change it now, there is too much code out there that relies on this exact behaviour.

There is however nothing that prevents you from detecting this kind of input data format and rewriting it into a form suitable for you.

<?php
$in = array();
$in['name'] = array('name1', 'name2', 'name3');
$in['tmp_name'] = array('tmpname1', 'tmpname2', 'tmpname3');


$files = array();

// remap input data into desired format
foreach (array_keys($in) as $field) {
    foreach ($in[$field] as $index => $item) {
        $files[$index][$field] = $item;
    }
}

print_r($in);
print_r($files);

If you run it, you get the following result.

[~]> php test.php
Array
(
    [name] => Array
        (
            [0] => name1
            [1] => name2
            [2] => name3
        )

    [tmp_name] => Array
        (
            [0] => tmpname1
            [1] => tmpname2
            [2] => tmpname3
        )

)
Array
(
    [0] => Array
        (
            [name] => name1
            [tmp_name] => tmpname1
        )

    [1] => Array
        (
            [name] => name2
            [tmp_name] => tmpname2
        )

    [2] => Array
        (
            [name] => name3
            [tmp_name] => tmpname3
        )

)

Substitute $in for $_FILES and you are done. As an additional gimmick the "remapping" code works for all arrays with similar structure as $_FILES

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜