Check file uploaded is in csv format

theking963 picture theking963 · Jul 11, 2011 · Viewed 105.7k times · Source

I am uploading a file in php and only want to upload it if it's a csv file. I believe my syntax is right for the content type. It always goes to else statement when it's a csv file. What I am doing wrong here?

if (($_FILES["file"]["type"] == "text/csv"))
{

}
else
{

}

If I change the content type it works for that format just not csv.

Answer

Alan Cole picture Alan Cole · Jul 11, 2011

the mime type might not be text/csv some systems can read/save them different. (for example sometimes IE sends .csv files as application/vnd.ms-excel) so you best bet would be to build an array of allowed values and test against that, then find all possible values to test against.

$mimes = array('application/vnd.ms-excel','text/plain','text/csv','text/tsv');
if(in_array($_FILES['file']['type'],$mimes)){
  // do something
} else {
  die("Sorry, mime type not allowed");
}

if you wished you could add a further check if mime is returned as text/plain you could run a preg_match to make sure it has enough commas in it to be a csv.