我喜欢@Lendrick 尝试重建数组。我完全同意原始的 $_FILES 数组在 PHP 中纯粹是疯狂的。
备选方案 1
我想出了这个支持多维数组的函数,比如<input type="file" name="a[b][c]" />
/*
* Return a sane list of uploaded files
* @author tim-international.net
*/
function get_uploaded_files() {
$result = [];
foreach (preg_split('#&#', http_build_query($_FILES, '&'), -1, PREG_SPLIT_NO_EMPTY) as $pair) {
list($key, $value) = explode('=', $pair);
$key = urlencode(preg_replace('#^([^\[]+)\[(name|tmp_name|type|size|error)\](.*)$#', '$1$3[$2]', urldecode($key)));
$result[] = $key .'='. $value;
}
parse_str(implode('&', $result), $result);
return $result;
}
示例输出<input type="file" name="image[]" multiple />
:
array(1) {
["image"]=>
array(1) {
[0]=>
array(5) {
["name"]=>
string(20) "My uploaded file1.png"
["type"]=>
string(9) "image/png"
["tmp_name"]=>
string(27) "C:\Windows\Temp\php6A8E1.tmp"
["error"]=>
int(0)
["size"]=>
int(26570)
}
[1]=>
array(5) {
["name"]=>
string(20) "My uploaded file2.png"
["type"]=>
string(9) "image/png"
["tmp_name"]=>
string(27) "C:\Windows\Temp\php6A8E2.tmp"
["error"]=>
int(0)
["size"]=>
int(26570)
}
}
}
使用示例:
$uploaded = get_uploaded_files();
foreach ($uploaded['image'] as $i => $file) {
move_uploaded_file($uploaded[$i]['tmp_name'], ...);
}
备选方案 2
另一个变体可以提供更扁平的数组,可以很方便的是:
function get_uploaded_files() {
$result = [];
foreach (preg_split('#&#', http_build_query($_FILES, '&'), -1, PREG_SPLIT_NO_EMPTY) as $pair) {
list($key, $value) = explode('=', $pair);
if (preg_match('#^([^\[]+)\[(name|tmp_name|type|size|error)\](.*)$#', urldecode($key), $matches)) {
$result[$matches[1].$matches[3]][$matches[2]] = urldecode($value);
}
}
return $result;
}
它返回以下内容<input type="file" name="foo[bar][]" multiple />
:
array(1) {
["foo[bar][0]"]=>
array(5) {
["name"]=>
string(20) "My uploaded file1.png"
["type"]=>
string(9) "image/png"
["tmp_name"]=>
string(27) "C:\Windows\Temp\php6A8E1.tmp"
["error"]=>
int(0)
["size"]=>
int(26570)
}
["foo[bar][1]"]=>
array(5) {
["name"]=>
string(20) "My uploaded file2.png"
["type"]=>
string(9) "image/png"
["tmp_name"]=>
string(27) "C:\Windows\Temp\php6A8E2.tmp"
["error"]=>
int(0)
["size"]=>
int(26570)
}
}
}
使用示例:
foreach (get_uploaded_files() as $field => $file) {
move_uploaded_file($file['tmp_name'], ...);
}