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.
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.
The code for validating whether its a csv file or not. use in_array($_FILES['file']['type'],$csvMimes) .
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 (,).
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.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With