Advices - on validation upload method

I’ve not tested yet but, I believe it will work. This pretends to be a method on a validation class that will allow to validate an uploaded file.

I’m far away from being considered a programmer, so I would like to ask you if it’s ok, and if, if there is something that really needs to change, what would your suggestions be?

Thanks in advance,
Márcio

At your consideration:

 /**
     *
     * @param <array> $campoForm
     * @param <int> $limiteKb
     * @return <boolean> 
     */
    public function validaUpload($campoForm, $limiteKb = null)
    {
        $nomeTemporario = $campoForm['tmp_name'];
        $codigoErro = $campoForm['error'];

        //se o upload NÃO foi OK - corre o switch
        if ($codigoErro != UPLOAD_ERR_OK)
        {
            switch ($codigoErro)
            {
                //valida o tamanho no php-ini e no MAX_FILE_SIZE no formulário - contudo, este último não é fiável pois, depende do user agent e do seu suporte para isso.
                case UPLOAD_ERR_INI_SIZE:
                case UPLOAD_ERR_FORM_SIZE:
                    $this->_msgErro[$campoForm] = 'Erro no upload: O tamanho do ficheiro é demasiadamente grande. Reduza as dimensões e tente novamente.';
                    break;

                case UPLOAD_ERR_PARTIAL:
                    $this->_msgErro[$campoForm] = 'Erro no upload: O ficheiro não foi enviado na totalidade. Tente novamente.';
                    break;

                case UPLOAD_ERR_NO_FILE:
                    $this->_msgErro[$campoForm] = 'Erro no upload: Nenhum ficheiro foi enviado.';
                    break;

                case UPLOAD_ERR_NO_TMP_DIR:
                    $this->_msgErro[$campoForm] = 'Erro no upload: A directoria de upload não foi encontrada.';
                    break;

                case UPLOAD_ERR_CANT_WRITE:
                    $this->_msgErro[$campoForm] = 'Erro no upload: Não foi possível escrever no ficheiro de envio.';
                    break;

                case UPLOAD_ERR_EXTENSION:
                    $this->_msgErro[$campoForm] = 'Erro no upload: A extensão não é suportada.';
                    break;

               default:
                   $this->_msgErro[$campoForm] = 'Erro no upload: Erro desconhecido.';
            }
        }

        //se o Upload foi OK mas, se o size for maior que o limite definido (independente do user agent), em KB:
        elseif (isset($limiteKb) && ($campoForm['size'] / 1024 > $limiteKb))
        {
            $this->_msgErro[$campoForm] = 'Erro no upload: O tamanho do ficheiro é maior que o limite especificado.';
        }
        //se o upload foi OK, se o filesize foi OK mas, se o ficheiro não veio do upload:
        elseif (!is_uploaded_file($nomeTemporario))
        {
            $this->_msgErro[$campoForm] = 'Erro no upload: Ficheiro não corresponde ao ficheiro enviado.';
        }
        else
        {
            //se tudo está ok, devolve true.
            return true;
        }
    }

I will grab is extension, and according to is extension the GD library should do it’s job. If we will crop, or resize horizontaly, it’s a job for our resizeImage class methods.

So we may have something like this:

$validation->validateUpload();
//if it is an image that we want to accept:
$validation->validateImage();
//then, we apply the resize if we need one:
$resize->$resizeHorizontal(); or $resizeAuto();

//and the end, and only at the end, we can then insert the data into the database: the image information, and the thumbnail information on their proper columns into image table.
$userDAO->insertUser(); 
$lastId = $userDao->lastIdfromInsert();
$image->$insertImage($lastId); //by using the last id on the where clause;

This is what I’m thinking of.
If it doesn’t make sense, please, let me know about it.

Thanks again,
Márcio

I would create a set of validators for each accepted upload type.


interface UploadValidator
{
  public function isValid();
}

class UploadValidatorFactory
{
  public static function Build($upload){
    #return an instance of a validator based on file type
  }
}

class UploadValidatorImage implements UploadValidator
{
  protected
    $image;

  public function isValid(){
    return $is_image;
  }
}

class UploadValidatorDocument implements UploadValidator
{
  protected
    $document;

  public function isValid(){
    return $is_document;
  }
}

Client code then, would just be…


if(UploadValidatorFactory::Build($upload)->isValid()){
  #yay
}

Or at least something similar.

Well, it’s sometimes funny to see how ignorant they can get :slight_smile:
But overall I’m afraid that I’m mostly the best user to use my systems …

Yes. I was wondering - should I have another method for validate images, then documents, then anythingElse ;

If so, maybe the extension validation could be done by validateImage(); in order to validate .jpg, .gif, .png …

validateUpload();
then…
validateImage(); if it’s an image.
Or, validateDoc() if it’s a document.

What do you think?

K. Regards,
Márcio

Extension checking is missing.

Ha, I can well believe it.

Users, boy, they’re fun aren’t they? :stuck_out_tongue:

You are a bonus giver this weekend! :wink:

I’ve seen this on some codes, the [2] and the [3] and other key numbers, and I’m wondering: 1) what do they mean? But I will search. Np. :slight_smile: And the next question was, why not use an associative array, so that we can understand what those keys means?

I thought that two :p, 15 years ago. But it’s not that stupid as you may think of at a first glass, I mean, I was imagining that, changing the extension, the file type will change as well, and that should be a OS work.
I still believe it could be a nice feature to have. You change the extension and the SO ask: “Do you wish to change the extension, or do you wish to convert this file?” :eye:

Nice! :slight_smile: I will !! Can we close the thread now? :D:D

Well, that gives me a boost, and I will code for more 10 hours now! Let’s see that I can get. :cool:

I’ve started to program at the same time I join sitepoint forums, and I sure have a big debt with this community already. But all will be payed back! :slight_smile:

Well, back to code. :slight_smile: And I will see what I can get, once this one is done, I’m sure ready for another, better then this one. :slight_smile:

Thanks,
Márcio

When validating uploaded image files, I always used to check the extension of the uploaded file. Until I found out some of my clients are under the impression you can convert a BMP to a JPEG by changing its extension. So they upload such a file and GDLib goes all kind of bonkers (my gd install can’t read bmp, I’m not sure if any gd install can).

Now I use $info = getimagesize() on the uploaded file and use $info[2] to see what kind of image we’re dealing with. This actually reports the correct filetype, preventing clients from sneeking in BMP’s disguised as JPEG files.

For those of you who wonder, I’m not kidding, some of my clients actually believe you can convert a BMP to a JPEG by changing its extension …

Also another thing is:
how would you handle image resizing when the upload is image type file?

Personally Márcio, after following your posts/threads here at Sitepoint, I think you’re coming on leaps and bounds!

You’re doing a cracking job, keep it up. :slight_smile:

Thanks. :slight_smile:

:rofl: That IS a very nice suggestion indeed! :slight_smile:

It seems a very clean code.
I will do it next time. First I need to understand what an interface is, and what implements does. And a Factory design pattern;
But I can grasp something from here already. :slight_smile: (I’m happy inside). I’m sure a few more months, and when I will need to change this, I will opt for something like this.

Two notes on sincerity from you guys:
What I’m trying to accomplish, is… like: bad ?
Or, is just something that could be better?

I’m sorry, but I have no reference points, so I’m trying to get some lights on my path.

Thanks in advance,
Márcio

What they mean you can find in the manual page on getimagesize
Why they chose to have it return an array with numeric keys rather than an assoc array beats me. :slight_smile:

That would be cool :cool:
Although that probably has its own problems. What if I rename an .avi to .txt, should the OS convert the whole avi to a really long ascii art file? :smiley: