atp

Atp's external memory

php annoyance multiple file uploads with $_FILES

This caused me to waste 1/2 an hour or so this morning. It also needed some quite precise google-fu to uncover the solution. I'm bound to forget this and am likely to need it again so it's going here. I'm not sure how most of the zillions of "upload multiple files with php" tutorials out there work, because none of them seem to mention this.

I was doing multiple file uploads in php, and finding that although you submit multiple files with a multipart/form-data encoding type (and can see multiple files being submitted in chrome devtools), php was only reporting the last one in the list of uploaded files in $_FILES. Very annoying.

In other words, I wanted $_FILES to contain this;

Array
(
[uploadfiles] => Array
(
[name] => Array
(
[0] => new_simulator_append.csv
[1] => mem_reclaim_on_node0.csv
)

[type] => Array
(
[0] => text/csv
[1] => text/csv
)

:

but got this;

Array
(
[uploadfiles] => Array
(
[name] => mem_reclaim_on_node0.csv
[type] => text/csv
:

even though I could see both files being POST'ed via the ajax call.

Even more strange was that I could see (after putting a sleep(30) call into the php) that both files were actually being put in the temporary directory. PHP was ignoring all but the last.

The answer was simply to change the name of the input.

So the HTML was;

<form method="post" enctype="multipart/form-data" id="datafiles" action="index.html" >
<input type="file" name="uploadfiles" id="blah" multiple />
<button type="submit" id="submitbtn">Upload Data</button>
</form>

and it needed to be;

<form method="post" enctype="multipart/form-data" id="datafiles" action="index.html" >
<input type="file" name="uploadfiles[]" id="blah" multiple />
<button type="submit" id="submitbtn">Upload Data</button>
</form>

Apparently, php uses "[]" on the end of the input elements name as a hint that there's a multiple set of files inbound, and not a single one. 

What's particularly galling is that the "uploading multiple files" part of the php docs "clearly" state this;

It is also possible to upload multiple files simultaneously and have the
information organized automatically in arrays for you. To do so, you need
to use the same array submission syntax in the HTML form as you do with
multiple selects and checkboxes:

So, if you're wondering why php only sees the last file in a multiple file upload, thats the cause. Add a [] to your form input name. 

I'm obviously far to used to php just doing what I meant, not what I say.

Written by atp

Monday 08 September 2014 at 12:09 pm

Posted in Annoyances, Linux

Leave a Reply