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.
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:
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'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:
the mime type might not be
text/csv
some systems can read/save them different. (for example sometimes IE sends .csv files asapplication/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.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.Mime type option is not best option for validating CSV file. I used this code this worked well in all browser
You can't always rely on MIME type..
According to: http://filext.com/file-extension/CSV
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.
Code untested.