Skip to content

Instantly share code, notes, and snippets.

@cballou
Created March 25, 2012 12:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cballou/2193503 to your computer and use it in GitHub Desktop.
Save cballou/2193503 to your computer and use it in GitHub Desktop.
Uploading Multiple Files in PHP – Fixing the Array Indices
<?php
// passed by reference
fixFilesArray($_FILES['fieldname']);
// all fixed
var_dump($_FILES['fieldname']);
<?php
$_FILES['fieldname']['name'][1] = 'uploadedfile.jpg';
$_FILES['fieldname']['name'][2] = 'uploadedfile2.jpg';
$_FILES['fieldname']['type'][1] = 'image/jpeg';
$_FILES['fieldname']['type'][2] = 'image/jpeg';
$_FILES['fieldname']['tmp_name'][1] = '/tmp/rAnDOmCHaRs';
$_FILES['fieldname']['tmp_name'][2] = '/tmp/RANdOmcHArs';
$_FILES['fieldname']['error'][1] = 0;
$_FILES['fieldname']['error'][2] = 0;
$_FILES['fieldname']['size'][1] = 1427;
$_FILES['fieldname']['size'][2] = 1576;
<?php
/**
* Fixes the odd indexing of multiple file uploads from the format:
*
* $_FILES['field']['key']['index']
*
* To the more standard and appropriate:
*
* $_FILES['field']['index']['key']
*
* @param array &$files
*
*/
function fixFilesArray(&$files)
{
// a mapping of $_FILES indices for validity checking
$names = array('name' => 1, 'type' => 1, 'tmp_name' => 1, 'error' => 1, 'size' => 1);
// iterate over each uploaded file
foreach ($files as $key => $part) {
// only deal with valid keys and multiple files
$key = (string) $key;
if (isset($names[$key]) && is_array($part)) {
foreach ($part as $position => $value) {
$files[$position][$key] = $value;
}
// remove old key reference
unset($files[$key]);
}
}
}
<?php
$_FILES['fieldname'][1]['name'] = 'uploadedfile.jpg';
$_FILES['fieldname'][1]['type'] = 'image/jpeg';
$_FILES['fieldname'][1]['tmp_name'] = '/tmp/rAnDOmCHaRs';
$_FILES['fieldname'][1]['error' = 0;
$_FILES['fieldname'][1]['size'] = 1427;
$_FILES['fieldname'][2]['name'] = 'uploadedfile2.jpg';
$_FILES['fieldname'][2]['type'] = 'image/jpeg';
$_FILES['fieldname'][2]['tmp_name'] = '/tmp/RANdOmcHArs';
$_FILES['fieldname'][2]['error'] = 0;
$_FILES['fieldname'][2]['size'] = 1576;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment