如何使用 Codeigniter 上传文件?

How to upload files using Codeigniter?

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

        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] 上收到此错误,因为文件 nametypetmp_name 是字符串值。

并且当您尝试将字符串值视为数组时,它将获取位置 [$i] 处的字符。这可能也不是您想要的,但它不会给出错误。)

解决方案是复制 $_FILES 数组并遍历副本,同时将值分配回 $_FILES 数组,如此处接受的答案所示: