Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Phalcon don't recognize HTML5 multiple file upload

Hi folks,

I'm testing a multiple file upload view, which have this structure:

<!-- ... -->
<form action="index" method="post" enctype="multipart/form-data">
    <input type="file" name="files" multiple>
    <input type="submit" value="Send File(s)">
</form>
<!-- ... -->

And then, in my controller I have this code to handle the files sent to it:

if($this->request->hasFiles() == true){
    foreach($this->request->getUploadedFiles() as $upload){
        $path = 'uploads/'.$upload->getname();
        $upload->moveTo($path);
    }
}

But for some reason the code above only works with one file. When I try to upload more than one file, it goes as normal (no errors or exceptions displayed), but only one file is uploaded.

When I use print_r to show what getUploadedFiles() is returning, there is always only one file in the array. But when I inspect the headers sent to it in the browser, there are all files I've choosen in the input.

Is this some kind of bug? For some reason Phalcon can't support HTML5's native multiple file upload? Or its me doing something wrong?



41.6k
Accepted
answer

I've found the solution. And it was pretty meh.

When using multiple HTML5 attribute to an input, in its name you must put [] in order to it pass all the selected files.

Example:

<!-- WRONG: This will return only one file in PHP -->
<input type="file" name="files" multiple>

<!-- RIGHT: This will return all uploaded files in an array in PHP -->
<input type="file" name="files[]" multiple>

Simple as that. So, it has nothing to do with Phalcon, or PHP.

I hope this help anyone have this almost untraceable yet so simple issue.



7.2k
{{ form('post/add', 'method': 'post', 'enctype': "multipart/form-data",'class':'form-post') }}
        $files = $this->request->getUploadedFiles();
        foreach ( $files as $file )
        {...}

and all works.