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

How to validate file upload ?

How to validate file upload , to make sure there is file being choose before submit form ?

I try to use Validator PresenceOf , but now working.



58.4k
edited Oct '14

Hey

In controller or any file, you must create function check it, for example below i will check format images

    /**
     * Attempt to determine the real file type of a file.
     *
     * @param  string $extension Extension (eg 'jpg')
     *
     * @return boolean
     */
    private function imageCheck($extension)
    {
        $allowedTypes = [
            'image/gif',
            'image/jpg',
            'image/png',
            'image/bmp',
            'image/jpeg'
        ];

        return in_array($extension, $allowedTypes);
    }

And now useage it

/**
     * Method changeAvatarAction
     *
     */
    public function changeAvatarAction()
    {
        //dosomething

        if ($this->request->hasFiles()) {
            foreach ($this->request->getUploadedFiles() as $file) {
                if ($this->imageCheck($file->getRealType())) {

                    $this->flashSession->success(t('Data was successfully saved'));
                } else {
                    $this->flashSession->error(t('We don\'t accept that kind of file. Please upload an image.'));
                }
            }
        }

        return $this->response->redirect($this->router->getControllerName() . '/profile');
    }