I have a form that allows the user to add as many upload forms as they want. So initially there’s one, and you can click “Add More” to… add more. Makes sense. Each input looks like this:
<input type="file" name="userfile[]" id="userfile[]">
But when you upload more than one file, only the first file gets uploaded. Below is my PHP. I’m using CodeIgniter and the File Upload library.
$dir = random_string('alnum', 10);
mkdir('/Applications/MAMP/htdocs/extras/uploads/temp/'.$dir);
$this->load->library('upload');
$error = 0;
for ($i = 0; $i < count($_FILES['userfile']['name']); $i++):
$_FILES['userfile']['name'] = $_FILES['userfile']['name'][$i];
$_FILES['userfile']['type'] = $_FILES['userfile']['type'][$i];
$_FILES['userfile']['tmp_name'] = $_FILES['userfile']['tmp_name'][$i];
$_FILES['userfile']['error'] = $_FILES['userfile']['error'][$i];
$_FILES['userfile']['size'] = $_FILES['userfile']['size'][$i];
$config['upload_path'] = '/Applications/MAMP/htdocs/extras/uploads/temp/'.$dir;
$config['allowed_types'] = 'jpg|jpeg|gif|png';
$this->upload->initialize($config);
if ($this->upload->do_upload('userfile')):
$error += 0;
else:
$error += 1;
endif;
endfor;
if ($error > 0):
$error = array('error' => $this->upload->display_errors());
print_r($error);
else:
$data = array('upload_data' => $this->upload->data());
print_r($data);
endif;
If I add an echo count($_FILES['userfile']['name']; before the for loop, it correctly displays the number of files. If I use it after the for loop, it incorrectly displays 1.
Any idea what I’m doing wrong here?
My best guess is that once you enter the loop you overwrite the values using these lines:
Try changing that to something like this:
And then using
if ($this->upload->do_upload('userfile_tmp')):