How to validate header of CSV file

I have a working CSV file upload controller/model/view that does some rudimentary checking of filesize and extension for validation.

I’d like to add a validator for the header. In my upload form, you choose the type of file from a dropdown menu and each type has a specific header signature. I am basically grabbing the first line of the file and using php in_array() function to determine if the key exists.

I currently have a static function in my Upload model class that is called outside of the validate call in the controller. I’d like to integrate this into the form and model validation so that any errors will display for the user using $this->addError. Something like ‘You have chosen a file of the wrong type’.

The problem I see is that the file is not uploaded until it passes validation - so how do you validate the contents??

I was reading the CUploadedFile class reference and it looks like there is a property called ‘tempName’ that may be used but wondering if anyone had insight.

I would do something like this:










function rules(){

 return array(






function validateCSV(){


  $this->addError('csv','Wrong file type!');



  $this->addError('csv','Oops! There is something wrong with your file! This is not a valid csv file !');



for reference: http://www.yiiframew…1/CUploadedFile

Also for better handling of mime types check http://www.yiiframew…per#getMimeType ( in this case you must use the tempName property to pass as 1º parameter)

That would be it if I understood you correctly

I don’t want to check if the file is a CSV - rather I need to actually analyze the header to make sure it has a particular column. My upload form can handle 3 different types of CSV files (they are log files of different types) and each has to go into a different DB table.

I think $model->csv->tempName should probably work before I call saveAs().

I will use fgetcsv to get the first line of the file and then use in_array() on that to search for the column that I need.