如何使用Codeigniter上传文件?

anauzrmj  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(136)

我用这个奇怪的代码上传文件:

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
taor4pac

taor4pac1#

你得到这个错误是因为你循环遍历一个数组并且在循环中修改了这个数组.
$_FILES['file']['error'][$i]是整数,因此在循环的第一次迭代中$_FILES['file']['error']变为整数。
在循环的第二次迭代中,当您尝试访问$_FILES['file']['error'][$i]时,它试图将现在位于$_FILES['file']['error']的整数视为数组并获取元素[$i],这是不可能的。
(You在$_FILES['file']['name'][$i]$_FILES['file']['type'][$i]$_FILES['file']['tmp_name'][$i]上不会收到此错误,因为文件nametypetmp_name是字符串值。
当你试图把一个字符串值当作一个数组时,它会得到位置[$i]的字符,这可能也不是你要找的,但它不会给予错误。)
解决方案是复制$_FILES数组,并在将值赋回$_FILES数组时循环副本,如下面的可接受答案所示:https://stackoverflow.com/a/11539061/3960296

相关问题