tags:

views:

66

answers:

1

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 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?

+4  A: 

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

Anti Veeranna
It would be good if you could provide a simple snippet for rejiging the FILES array for people.
Question Mark
Of course, sample code added now
Anti Veeranna
Thanks, I solved it that way, I know, it's not really difficult. The point is as you said, it was an unfortunate desicion. I don't know, maybe the HTML5 spec could have included an attribute for the <input type='file'/> that makes the array be formed this way.
Petruza