We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

$request->hasFiles() return 1 when expecting 0 as no files attached

Ok so I have a multipart form:

<form id="form" method="post" enctype="multipart/form-data">
    <input type="file" name="upload_avatar">
    <input type="submit" value="Update" name="update_profile">
</form>

When I submit the form from the perspective of the controller action then

$this->request->hasFiles() ;

returns 1 wether a file exists or not.

As far as I can tell all it is testing for is the precense of the html input element of type file.

So my question is can anyone provide a solid example of the right context to use $this->request->hasFiles() as I'm having trouble seeing its use.

The reason is that what I want to quickly check to see that the post actually has a file attached.

Does anyone have a sensible comment? Apologies but I have found this very frustrating.



47.7k

I found this worked:

if( $this->request->getUploadedFiles(true) == true ) {
    //Do stuff with file
} else {
    //Continue operating as with no file
}

also

if( $this->request->hasFiles(true) == true ) {
    //Operate as with files
} else {
    //Operate as with no files
}


950

I wrote it in my code, because the user can upload some images or not

if($this->request->hasFiles()) {
        foreach ($this->request->getUploadedFiles() as $file) {
               $file->moveTo($this->url->getBasePath() . 'img/' . $file->getName());
        }
}