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

uploading files

How i can upload files to the server???

in the documentation comes:


public function uploadAction()
    {
        // Check if the user has uploaded files
        if ($this->request->hasFiles() == true) {
            // Print the real file names and sizes
            foreach ($this->request->getUploadedFiles() as $file) {

                //Print file details
                echo $file->getName(), " ", $file->getSize(), "\n";

                //Move the file into the application
                $file->moveTo('files/');
            }
        }
    } ```

https://docs.phalcon.io/en/latest/reference/request.html#uploading-files

but $file->moveTo() throws me the error

```php<b>Warning</b>:  move_uploaded_file(): The second argument to copy() function cannot be a directory in <b>/var/www/html/phalcon/apps/Inteligob/Controllers/BlobsController.php</b> on line <b>59</b><br />
<br />
<b>Warning</b>:  move_uploaded_file(): Unable to move '/tmp/phpeK80pt' to 'upload/' in <b>/var/www/html/phalcon/apps/Inteligob/Controllers/BlobsController.php</b> on line <b>59</b><br />```


98.9k
edited Jul '19

Normally PHP sends the mime type in the 'type' index of every file in $_FILES, however that index could be easily changed by an attacker to cheat an application:

https://stackoverflow.com/a/1615002/1022921

You can better use the fileinfo (https://php.net/manual/en/function.finfo-open.php) function to get the right mime type once the file is uploaded:

public function uploadAction()
{        
    if ($this->request->hasFiles() == true) {           
        $fi = new finfo(FILEINFO_MIME, '/usr/share/misc/file/magic');
        foreach ($this->request->getUploadedFiles() as $file) {
            echo 'Mime = ', $fi->file($file->getTempName()), '<br>';                 
        }
    }
}


36.8k

thanks, i resolved that with the fileinfo function, but now i have another problem, in fact i change the post, can you help me ??



98.9k

It must be:

$file->moveTo('files/' . $file->getName());
edited Jul '19

For future readers:

  • In moveTo method you must specify the complete path of new file (including filename);
  • The mime possible issue is now solvable using $file->getRealType() method that uses finfo as explained above.