Reply to Re: multiple files upload

Re: multiple files upload new!
by colin, 17 years, 10 months ago
If you have multiple upload fields, they will have the same name, right?

So assuming that you have three of these upload fields, called my_field[], and that the user enters a file for the first and third field only, $_FILES will be as following:
Array
  [my_field] => Array
    [name] => Array
      [0] => P1040124.JPG
      [1] => 
      [2] => P1040281.JPG
    [type] => Array
      [0] => image/jpeg
      [1] => 
      [2] => image/jpeg
    [tmp_name] => Array
      [0] => /tmp/php0bMcTr
      [1] => 
      [2] => /tmp/phpxf9Rr5
    [error] => Array
      [0] => 0
      [1] => 4
      [2] => 0
    [size] => Array
      [0] => 2959714
      [1] => 0
      [2] => 2329004

We need to re-organize the array for the class, with.
$files = array();
foreach ($_FILES['my_field'] as $k => $l) {
 foreach ($l as $i => $v) {
 if (!array_key_exists($i, $files)) 
   $files[$i] = array();
   $files[$i][$k] = $v;
 }
}

So we have now in $files:
Array
  [0] => Array
    [name] => P1040124.JPG
    [type] => image/jpeg
    [tmp_name] => /tmp/php7aqJYX
    [error] => 0
    [size] => 2959714
  [1] => Array
    [name] => 
    [type] => 
    [tmp_name] => 
    [error] => 4
    [size] => 0
  [2] => Array
    [name] => P1040281.JPG
    [type] => image/jpeg
    [tmp_name] => /tmp/phpKet10G
    [error] => 0
    [size] => 2329004

So we need to modify our loop so that $files doesn't include the second entry in the array, which is for the non-uploaded file. So the loop becomes:
$files = array();
foreach ($_FILES['my_field'] as $k => $l) {
  foreach ($l as $i => $v) {
    if (!array_key_exists($i, $files)) 
      $files[$i] = array();
    $files[$i][$k] = $v;
  }
}
// we now remove invalid entries for non-uploaded images
foreach ($files as $k => $v) {
  if ($v['error'] != 0) unset($files[$k]);
}

So now you can feed $files into class.upload.php, for instance doing as following:
foreach (array_keys($files) as $k) {
  $handle = new upload($files[$k]);
  // process your upload here
}
Reply

Your reply

Name *
Email 
Title *
Text *
CAPTCHA image
Enter the code displayed on the image:
Click on the image to generate another one if it is hard to read it. The case is important