Search code examples
javascriptphpfile-upload

Upload files - array created in wrong way?


I have tried multiple uploads via

      <input type="file" class="file-upload-field" id="file_name" name="files_names[]" multiple="multiple" />

and my javascript/jquery code looks like this : (taken from other SoF articles)

$(document).on('submit', '#addform', (function() {
var files = $('#file_name')[0].files;
var formData = new FormData();

for (var i=0; i < files.length; i++)
  formData.append('file_names[]', files[i]);

  $.ajax({
    url: 'ajax_addrecord.php',
        type: "POST",
  data: formData,
  contentType: false,
  cache: false,
  processData:false,
  timeout: 2000,
    success: function(data) {
      console.log('Record added.');
    }
  });

}));

but when I do this in my PHP file (just to check if the files arrive ok)

error_log($date_time." :: ".print_r($_FILES, true), 0);

the result is as follows:

 2024-03-03 11:14:47 :: Array
 (
     [file_names] => Array
         (
             [name] => Array
                 (
                     [0] => HeleneBarrow Profil.png
                     [1] => horn_fuuuck_lovers.JPG
                     [2] => lakn_profil_mona.JPG
                 )
             [type] => Array
                 (
                     [0] => image/png
                     [1] => image/jpeg
                     [2] => image/jpeg
                 )
             [tmp_name] => Array
                 (
                     [0] => /tmp/phpZ3FVIl
                     [1] => /tmp/phpvolre9
                     [2] => /tmp/phpp4gYJW
                 )
             [error] => Array
                 (
                     [0] => 0
                     [1] => 0
                     [2] => 0
                 )
             [size] => Array
                 (
                     [0] => 270198
                     [1] => 12359
                     [2] => 82773
                 )
         )

Expected result should look like this:

  [file_names] => Array
    [0] => {
      (
        [name] => HeleneBarrow Profil.png
        [type] => image/png
        [tmp_name] => /tmp/phpNmM8Se
        [error] => 0
        [size] => 270198
      )
    }
    [1] => {
      (
        [name] => horn_fuuuck_lovers.JPG
        [type] => image/jpeg
        [tmp_name] => /tmp/phpvolre9
        [error] => 0
        [size] => 270198
      )
    }
    [2] => {
      (
        [name] => lakn_profil_mona.JPG
        [type] => image/jpeg
        [tmp_name] => /tmp/phpp4gYJW
        [error] => 0
        [size] => 270198
      )
  }

It seems it segments the array per attribute instead of per image. Anyone see where I am going wrong?

Best regards,

Lars


Solution

  • You did nothing wrong, that just the way how PHP will fill the $_FILES array. The number 1 answer, 18 years old now, gives you a possible solution

    https://www.php.net/manual/en/features.file-upload.multiple.php