Martin Bean
Martin Bean

Reputation: 39389

Is application/octet-stream a safe MIME type to accept when accepting CSV files?

I'm building a web form to take a CSV file to then import the contents into a contacts database. However, during development I've noticed when uploading a CSV file the MIME type available to me is application/octet-stream.

A quick web search on Google tells me that application/octet-stream is a generic MIME type for binary files, which could be anything from a .csv to a .exe file, which doesn't seem safe to me as then the only other piece of information I have to determine the file type is the original filename. And this can easily be changed by any one with basic computing knowledge.

How can I ensure that a CSV file uploaded via a web form in PHP is actually a CSV file with the above information?

Upvotes: 8

Views: 10812

Answers (3)

oezi
oezi

Reputation: 51797

to validate a file, you shouldn't depend on the mime-type as this can easily be manipulated. same thing for file-extension. it just takes 15 seconds to bypass this kind of "security checks".

the only safe way is to check the content of the file to see if it contains valid csv-data.

Upvotes: 1

ChrisH
ChrisH

Reputation: 1281

When uploading files, you should never, never rely on MIME-types. They can be altered by the user.

Upvotes: 0

Michiel Pater
Michiel Pater

Reputation: 23023

That is correct, application/octet-stream is a generic MIME type.

You could check whether the file has the CSV extension and use the function fgetcsv() to determine whether the content of the file is valid. This function will return NULL or boolean false if there are problems reading the file as CSV.

Upvotes: 7

Related Questions