Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check file uploaded is in csv format

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.

like image 774
theking963 Avatar asked Jul 11 '11 18:07

theking963


People also ask

How do you check if a file is a CSV?

Count the number of commas in the file per line, there should normally be the same amount of commas on each line of the file for it to be a valid CSV file.

How can I tell if a file is CSV in PHP?

The code for validating whether its a csv file or not. use in_array($_FILES['file']['type'],$csvMimes) .

How do I know if a CSV file is comma delimited?

Adding "sep=;" or "sep=," to the CSV To do this: Open your CSV using a text editor. Skip a line at the top, and add sep=; if the separator used in the CSV is a semicolon (;), or sep=, if the separator is a comma (,).

How do I view a CSV file online?

Just enter the location of the file you want to check, or upload it. If you have a schema which describes the contents of the CSV file, you can also give its URL or upload it. CSVLint currently only supports validation of delimiter-separated values (dsv) files.


2 Answers

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.

like image 176
Alan Cole Avatar answered Oct 14 '22 16:10

Alan Cole


There are a lot of possible MIME types for CSV files, depending on the user's OS and browser version.

This is how I currently validate the MIME types of my CSV files:

$csv_mimetypes = array(     'text/csv',     'text/plain',     'application/csv',     'text/comma-separated-values',     'application/excel',     'application/vnd.ms-excel',     'application/vnd.msexcel',     'text/anytext',     'application/octet-stream',     'application/txt', );  if (in_array($_FILES['upload']['type'], $csv_mimetypes)) {     // possible CSV file     // could also check for file content at this point } 
like image 32
ukliviu Avatar answered Oct 14 '22 16:10

ukliviu