Question

I have a file input that selects multiple files that looks like this:

<input type = 'file' name = 'file[]' id = 'file' class = 'file' multiple = 'multiple' />

When the user chooses a file (or files), using Javascript I update the id and class to 'oldFile', then prepend another file input, but with file2[] instead of file[]. This happens as long as the user keeps picking files. Then, when the user submits the form the files get sent to my PHP script. I have tried two ways of counting the files, shown below.

The first is a simple

$files = count($_FILES);

The second is

$f = 0;
foreach($_FILES as $b)
{
    $f++;
}
$files = $f;

However, when I select files in a certain order, it returns an incorrect count.

If I select two files, then one file, then two files and submit the form, it says I submitted 4 files.

If I select two files then one file, it correctly says 3 files.

Any idea what the problem could be (not sure if I'm making sense)?

Was it helpful?

Solution

PHP's $_FILES is a bit wonky when you use array-based file upload names as you are. The structure created, in that case, is actually

$_FILES = array(
   'name' => array(
      0 => 'name of first file'
      1= > 'name of second file'
      etc...
   'type' => array(
      0 => 'type of first file',
      1 => 'type of second file'
   etc..
);

meaning that you'll get a constant count($_FILES) matching the number of fields tracked within an upload. To get an accurate count of how many files were uploaded, you need to count one of the sub-keys, eg.

count($_FILES['name']);

Don't ask me why it was done this way. PHP's design is already stupid enough, and this just one of many examples proving its bedrock stupidity.

A more sensible/sane designer would have used

$_FILES = array(
   0 => array(... all data about file #1),
   1 => array('... all data about file #2),
   etc...
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top