How do I retrieve the content-type of a file using PHP?
I don’t want to rely on the file extension alone.
Thanks!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Because files themselves don’t necessarily store the mime-type, you have to use a variety of methods to get hints to what the correct type is. If you know the file is an image, use http://www.php.net/manual/en/function.getimagesize.php … and you can check if a .doc or .xsl “looks like” what the extension claims it to be, because those file types always start with the same set of bytes http://filext.com/file-extension/DOC (see “identifying characters”). In some cases it would be very difficult to determine without relying on an extension (for instance what’s the difference between text/plain and text/css apart from the .css, unless you were to parse the file and account for every possible text type?)
In the end, the more you know about the file types you’re interested in, the more you can use that to verify a file to be of that type, and the more you spend writing code to do that job, the better the chances of you determining the correct mime-type!