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?
That is correct,
application/octet-streamis 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.