加载多个文件背后的PHP机制


php mechanism behind loading multiple files

我正在做一个多文件上传表单,我已经成功地使它与这个网站的帮助。现在我需要知道并理解它是如何工作的,这样我就可以不只是复制代码。

我们在HTML中有一个上传输入:

<input type="file" name="file[]" multiple />

所有的都保存在一个php变量中:

$_FILES['file']['tmp_name'][$i]

如何在括号name="file[]"创建一个三维的数组像这样?我更愿意想象这样一行:$_FILES['file[$ I]']['tmp_name']。为什么没有他们就不行呢?谢谢你!

它遵循所有其他名称的模式:如果您将[]附加到名称后,PHP将为您创建一个数组。就这么简单。

/foo.php?bar[]=baz&bar[]=42

这将导致:

$_GET['bar'][0] = 'baz'
$_GET['bar'][1] = '42'

与表单输入相同:

<input name="foo[]">

这将创建一个多维$_POST数组:

$_POST['foo'][..]

$_FILES的唯一区别是结构稍微不直观。这不是:

$_FILES['foo'][0]['tmp_name']
$_FILES['foo'][0]['name']
$_FILES['foo'][1]['tmp_name']
$_FILES['foo'][1]['name']
...

而是:

$_FILES['foo']['tmp_name'][0]
$_FILES['foo']['name'][0]
$_FILES['foo']['tmp_name'][1]
$_FILES['foo']['name'][1]

事情就是这样。是的,这个API本来可以设计得更好,但那样的话就会有很多PHP了。

既然你要上传(可能)多个文件,就必须有一种正确保存它们的方法。

所以系统是这样的:

$_FILES: 
The superglobal where the FILES will be saved
['file']: 
In this array the actual FILEDATA will be saved.
Another possibilty at this localtion would be ['error'], 
where outcoming error within the upload will be stored.
['tmp_name']:
Here you can access all the file names that were uploaded
Another possibilty on this possition would be ['type'],
where the type of the file will be stored (e.g. 'text/html')
[$i] is there to identify the exact file you within the uploaded files.

摘自官方文档,这里有一个例子:

array(1) {
    ["files"]=>array(2) {
        ["tmp_name"]=>array(2) {
            [0]=>string(9)"file0.txt"
            [1]=>string(9)"file1.txt"
        }
        ["type"]=>array(2) {
            [0]=>string(10)"text/plain"
            [1]=>string(10)"text/html"
        }
    }
}

希望清楚易懂!