I have a file input which is an array but what I had previously no longer works, it seems to throw an error for multiple files, it just uploads the latest file. I can’t figure out what I have done wrong.
<input type="file" name="userfile[]" id="userfile" class="multi" />
Then in my controller:
$upload_files = $_FILES;
var_dump($upload_files['userfile']['name']);
// get the selected files out of the array
for($i = 0; $i < count($upload_files['userfile']['name']); $i++) {
$_FILES['userfile'] = array(
'name' => $upload_files['userfile']['name'][$i],
'type' => $upload_files['userfile']['type'][$i],
'tmp_name' => $upload_files['userfile']['tmp_name'][$i],
'error' => $upload_files['userfile']['error'][$i],
'size' => $upload_files['userfile']['size'][$i]
);
You’re overwriting
$_FILES['userfile']on each iteration of the array (which is why only the last file is uploaded).Create a new array element each time it loops.
Also, change your loop to iterate over
$upload_files['userfile']instead of$upload_files['userfile']['name']as suggested in the above comments 🙂Just a pointer – it is better to assign
count($upload_files['userfile'])to a variable outside of yourforloop. It probably won’t make much difference if your array only has a few elements, but has massive performance benefits when working with large arrays.Check out http://www.phpbench.com/