RSS 2.0 Feed
Posted on March 25th, 2010 at 03:41 PM by Corey Ballou

PHP inherently makes parsing an array of uploaded files more difficult than it needs to be due to the ordering of it’s array indices. Below is a quick example array:

$_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;

To combat this, we could create a function to reassemble the multi-dimensional array so that it is based on index rather than key. This allows for easier iteration of files. Here’s an example of the reindex $_FILES['fieldname'] array:

$_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;

And the code that made it all happen:

/**
 * 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']
 *
 */
function fixFilesArray(&$files)
{
	$names = array( 'name' => 1, 'type' => 1, 'tmp_name' => 1, 'error' => 1, 'size' => 1);

	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]);
		}
	}
}

Sample usage:

// passed by reference
fixFilesArray($_FILES['fieldname']);

// all fixed
var_dump($_FILES['fieldname']);

Related Posts

Leave a Reply

Allowable tags
a, abbr, b, blockquote, cite, code, em, i, strike, strong, pre lang, line

* comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.