I am working on a script that will process user uploads to the server, and as an added layer of security I\'d like to know:
Is there a way to detect a file\'s true e
In *nix, the first two bytes of the file tells you (see "magic number"). In Windows, ...sometimes this will be true ("header info"). It is, ultimately, O.S. dependent.
Is checking the MIME type simply enough? I am assuming that changing the extension on a file doesn't change it's MIME type?
Is MIME type a strong enough indicator to go by here?
Thanks for all of the responses thus far.
Others have already mentioned FileInfo, which I think is the correct solution, but I'll add this just in case you can't use that one for some reason. Most (all?) *nix distros include a command called file
that when run on a file will output its type. It has a switch to output in human readable format (default) or the MIME type. You could have your script invoke this program on the uploaded file and read the result. Again, this is not the preferred approach. If you're on Windows, this utility is available through Cygwin.
Not really, no.
You will need to read the first few bytes of each file and interpret it as a header for a finite set of known filetypes. Most files have distinct file headers, some sort of metadata in the first few bytes or first few kilobytes in the case of MP3.
Your program will have to simply try parsing the file for each of your accepted filetypes.
For my program, I send the uploaded image to imagemagick in a try-catch block, and if it blows up, then I guess it was a bad image. This should be considered insecure, because I am loading arbitrary (user supplied) binary data into an external program, which is generally an attack vector. here, I am trusting imageMagick to not do anything to my system.
I recommend writing your own handlers for the significant filetypes you intend to use, to avoid any attack vectors.
Edit: I see in PHP there are some tools to do this for you.
Also, MIME types are what the user's browser claims the file to be. It is handy and useful to read those and act on them in your code, but it is not a secure method, because anyone sending you bad files will fake the MIME headers easily. It's sort of a front line defense to keep your code that expects a JPEG from barfing on a PNG, but if someone embedded a virus in a .exe and named it JPEG, there's no reason not to have spoofed the MIME type.
you can use below code which gives you MIME type if you have changed the extension then also
$finfo = finfo_open(FILEINFO_MIME_TYPE);
echo $mime = finfo_file($finfo, $_FILES['userfile']['tmp_name']);
finfo_close($finfo);
Windows users: just edit php.ini and uncomment this line:
extension=php_fileinfo.dll
Remember to restart Apache for new php.ini to take effect.