[php] 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.

This question is related to php syntax file-upload content-type

The answer is


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.


simple use "accept" and "required" in and avoiding so much typical and unwanted coding.


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
}

As you are worried about user upload other file by mistake, I would suggest you to use accept=".csv" in <input> tag. It will show only csv files in browser when the user uploads the file. If you have found some better solution then please let me know as I am also trying to do same and in the same condition - 'trusted users but trying to avoid mistake'


You can't always rely on MIME type..

According to: http://filext.com/file-extension/CSV

text/comma-separated-values, text/csv, application/csv, application/excel, application/vnd.ms-excel, application/vnd.msexcel, text/anytext

There are various MIME types for CSV.

Your probably best of checking extension, again not very reliable, but for your application it may be fine.

$info = pathinfo($_FILES['uploadedfile']['tmp_name']);

if($info['extension'] == 'csv'){
 // Good to go
}

Code untested.


Mime type option is not best option for validating CSV file. I used this code this worked well in all browser

$type = explode(".",$_FILES['file']['name']);
if(strtolower(end($type)) == 'csv'){

}
else
{

}

So I ran into this today.

Was attempting to validate an uploaded CSV file's MIME type by looking at $_FILES['upload_file']['type'], but for certain users on various browsers (and not necessarily the same browsers between said users; for instance it worked fine for me in FF but for another user it didn't work on FF) the $_FILES['upload_file']['type'] was coming up as "application/vnd.ms-excel" instead of the expected "text/csv" or "text/plain".

So I resorted to using the (IMHO) much more reliable finfo_* functions something like this:

$acceptable_mime_types = array('text/plain', 'text/csv', 'text/comma-separated-values');

if (!empty($_FILES) && array_key_exists('upload_file', $_FILES) && $_FILES['upload_file']['error'] == UPLOAD_ERR_OK) {
    $tmpf = $_FILES['upload_file']['tmp_name'];

    // Make sure $tmpf is kosher, then:

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime_type = finfo_file($finfo, $tmpf);

    if (!in_array($mime_type, $acceptable_mime_types)) {
        // Unacceptable mime type.
    }
}

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to syntax

What is the 'open' keyword in Swift? Check if returned value is not null and if so assign it, in one line, with one method call Inline for loop What does %>% function mean in R? R - " missing value where TRUE/FALSE needed " Printing variables in Python 3.4 How to replace multiple patterns at once with sed? What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript? How can I fix MySQL error #1064? What do >> and << mean in Python?

Examples related to file-upload

bootstrap 4 file input doesn't show the file name How to post a file from a form with Axios File Upload In Angular? How to set the max size of upload file The request was rejected because no multipart boundary was found in springboot Send multipart/form-data files with angular using $http File upload from <input type="file"> How to upload files in asp.net core? REST API - file (ie images) processing - best practices Angular - POST uploaded file

Examples related to content-type

Passing headers with axios POST request Spring MVC 4: "application/json" Content Type is not being set correctly What are all the possible values for HTTP "Content-Type" header? New lines (\r\n) are not working in email body HTML Input="file" Accept Attribute File Type (CSV) How do you set the Content-Type header for an HttpClient request? Utility of HTTP header "Content-Type: application/force-download" for mobile? Set Content-Type to application/json in jsp file Cannot set content-type to 'application/json' in jQuery.ajax Difference between application/x-javascript and text/javascript content types