我用这个奇怪的代码来上传文件:
if (!empty($_FILES['file']['name']) && count(array_filter($_FILES['file']['name'])) > 0) {
$filesCount = count($_FILES['file']['name']);
for ($i = 0; $i < $filesCount; $i++) {
$_FILES['file']['name'] = $_FILES['file']['name'][$i];
$_FILES['file']['type'] = $_FILES['file']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['file']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['file']['error'][$i];
$_FILES['file']['size'] = $_FILES['file']['size'][$i];
/* File upload configuration */
$uploadPath = 'uploads/reviews/';
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'jpg|jpeg|png|gif';
/* $config['max_size'] = '100'; */
/* $config['max_width'] = '1024'; */
/* $config['max_height'] = '768'; */
/* Load and initialize upload library */
$this->load->library('upload', $config);
$this->upload->initialize($config);
/* Upload file to server */
if ($this->upload->do_upload('file')) {
/* Uploaded file data */
$fileData = $this->upload->data();
$uploadData[$i]['file_name'] = $fileData['file_name'];
$uploadData[$i]['uploaded_on'] = date("Y-m-d H:i:s");
} else {
}
}
}
但是我想知道为什么它重写了一个$_FILES
,为什么我在网上得到错误:
`$_FILES['file']['error'] = $_FILES['file']['error'][$i];`
错误是:
Message: Trying to access array offset on value of type int
你得到错误是因为你在一个数组上循环并在循环中修改相同的数组。
$_FILES['file']['error'][$i]
是一个整数,因此在循环的第一次迭代中,$_FILES['file']['error']
成为一个整数。
在循环的第二次迭代中,当您尝试访问$_FILES['file']['error'][$i]
时,它试图将现在位于$_FILES['file']['error']
的整数视为数组并获取元素[$i]
,这是不可能的。
(您不会在$_FILES['file']['name'][$i]
,$_FILES['file']['type'][$i]
和$_FILES['file']['tmp_name'][$i]
上得到此错误,因为文件name
,type
和tmp_name
是字符串值。
当您尝试将字符串值视为数组时,它将获得位置[$i]
的字符。这可能也不是你想要的,但它不会给出一个错误。)
解决方案是复制$_FILES
数组,并在将值赋给$_FILES
数组的同时循环复制,如这里所接受的答案:https://stackoverflow.com/a/11539061/3960296