Sad to say, there is no perfect way to do so in any programming language.
The 2 most standard way to get the minetype is
- Determine from the file extension... So something.jpg is a jpeg file and something.doc is a word document.
- Determine from the magic string in the file... so if the first 2 bytes of the file is 0xFF 0xD8, it's a jpeg file. and a office document begins with 0xD0 0xCF 0x11 0xE0.
Both ways have pros and cons.
I can upload a exe file, but have it named with the extension of ".jpg" to defeat the first way or determining mime type.
And for both types, I basically need a large database to search from so that i can tell what mimetype the file belongs to.
However, if you are only interested in determining the mimetype for a few types of files. (Maybe just jpg, png, gif, etc), then the best way (imho) would be way number 2. Just keep a database or array of all the magic strings, and test the file against that.
It is easy to get the magic strings, just Google.