I don’t often have to deal with file uploads, but this morning I had to include one on a form I was developing for a project at work. I know Kohana has a decent Validation class and even provides an Upload helper for actually moving the file into place, but the examples were all spotty and / or confusing in different ways.

To help anyone else who may stumble upon this problem in the future, I thought I’d throw together a quick example.

The first and most important point, which was omitted in most of the documentation I found, is that you have to create a new Validation object for the $_FILES array, since PHP handles file uploads in a completely different superglobal from regular POST’d content.

Then you can build out your POST validation rules, just like always, using the $post validation object.

Now comes the special part, building out the validation rules for the file uploads as well. Note that the “name” field on my file upload element is “form”, this works just like any other POST’d field.

You can read the function documentation for not_empty and valid, but essentially it just makes sure that a file was uploaded and PHP accepted it without any problems.

Now that you’ve got your rules defined, you simply need to check both validation objects, just like you normally do.

Don’t forget to fetch errors from your file validation object too, or people won’t know why their form is failing. You can easily merge both sets of errors into a single array for display:

Lastly, don’t forget that you have to manually set the enctype of your form so that file uploads work properly. You can do this manually if you’re using HTML, or simply add it to the attributes array if you’re using the Form helper:

And that’s all there is to it, file uploads couldn’t be easier — once you have some decent documentation!

Originally published .
comments powered by Disqus