I use this strange code to upload files:
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 {
}
}
}
But I wonder why it rewrites a $_FILES
and why I get error on line:
`$_FILES['file']['error'] = $_FILES['file']['error'][$i];`
Error is:
Message: Trying to access array offset on value of type int
CodePudding user response:
You're getting the error because you're looping over an array and modifying that same array within the loop.
$_FILES['file']['error'][$i]
is an integer, so in the first iteration of the loop $_FILES['file']['error']
becomes an integer.
In the second iteration of the loop, when you try to access $_FILES['file']['error'][$i]
, it is trying to treat the integer that is now at $_FILES['file']['error']
as an array and get element [$i]
, which is impossible.
(You're not getting this error on $_FILES['file']['name'][$i]
, $_FILES['file']['type'][$i]
and $_FILES['file']['tmp_name'][$i]
because the file name
, type
and tmp_name
are string values.
And when you try to treat a string value as an array, it will get the character at position [$i]
. Which probably isn't what you were looking for either, but it does not give an error.)
The solution is to copy the $_FILES
array and loop over the copy while assigning the values back to the $_FILES
array, as in the accepted answer here: https://stackoverflow.com/a/11539061/3960296