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

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

It will be more readable



2.7k

Hi, please rewrite your code from Controller using

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



6.0k
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?



2.7k

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.