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.

Upload file check extension

Hi ..... my code not validate file extension and all test upload say "Field file must not be empty"

Model :

use Phalcon\Validation;
use Phalcon\Validation\Validator\Digit as DigitValidator;
use Phalcon\Validation\Validator\File as FileValidator;

    class Post extends \Phalcon\Mvc\Model
     {

      public function validation()
      {
          $validator  = new Validation();

          $validator->add('title', new DigitValidator([
              'message' => ':field must be numeric'
          ]));

          $validator->add('file', new FileValidator([
              'maxSize' => '2M',
              'messageSize' => ':field exceeds the max filesize (:max)',
              'allowedTypes' => array('image/jpeg', 'image/png'),
              'messageType' => 'Allowed file types are :types',
              'maxResolution' => '800x600',
              'messageMaxResolution' => 'Max resolution of :field is :max'
          ]));

          return $this->validate($validator);
      }
    }


    Controller :

    if ($this->request->hasFiles()) {
             foreach ($this->request->getUploadedFiles() as $file) {
                 $file->moveTo(
                      "files/" . (new Random())->uuid() . "." . $file->getExtension()
                     );
                 /*if ($this->imageCheck($file->getRealType())) {
                        $file->moveTo(
                            "files/" . (new Random())->base64Safe() . "." . $file->getExtension()
                       );
                   }else {
                         throw new Exception("Invalid Extension", 1);
                   }*/
                 }    
            }

Hi, please rewrite your code from Controller using ```php ``` It will be more readable

Hi, please rewrite your code from Controller using ```php ``` It will be more readable

i think problem is model beacuse when file upload or does not upload flash error is => filed file must not be empty && not prevent extension



3.8k
Accepted
answer

Thanks, I'm not so good at validation in models but this code should check your extension of uploaded file:

<?php
$ext = $file->getRealType(); 
$white_list_ext = array("image/jpeg", "image/png", "image/jpg", "image/bmp", "image/svg+xml");
        if (in_array($ext, $white_list_ext))
            {
                //continue
            }
        else
            {
                //bad ext
            }

Maybe im blind, but where are you creating post object etc stuff?

Maybe im blind, but where are you creating post object etc stuff?

This is example .... not real project :|

Then it's worst possible example because you are not accessing anywhere Post class.