CakePHP file upload validation

If you want to achieve file upload validation trough your CakePHP model, you can use the following code. For this tutorial I you have a database table with a field ‘pdf_path’ (of course, this can be anything you like).

First create a form input field using the CakePHP FormHelper class in your view file

Now set the validate array in your model.  I will put two validation rules

  1. Validate the extension of the file (if you want multiple extensions, just fill up the array)
  2. Validate against a custom validation function. The name of the function is the name you pass into the array. In this case this is ‘uploadFile’.

Now you just have to write the code to validate your upload and if everything goes according to plan, you can upload your file.

First I shift the array, so we can easily access the data from our POST request. Then I do some basic checks (you can extend these to your needs if you want better validation errors, but for the sake of not making this post to long … :)).

If we don’t find any errors, I create the path (this is relative to the webroot directory) and a unique file name.  You can generate a UDID or whatever you want, but time() will do the job just fine. Then we check if the folder exists, and if it doesn’t you create it.

Now we just need to move the file from its temporary directory on the server to its final destination.  Afterwards I set the pdf_path key in my model to the correct filename, so it will be saved in the database.

Then you can return true and the validation will be ok, or return false and then the error message will be shown.