When accepting user uploads, it's very important to check what they are uploading is actually what they say it is. Some scenarios are probably "unlikely", but all the same, it's wise to protect yourself as best you can.
Checking the file extension is not a bad start to make sure someone isn't uploading an executable file. The best method imo is to create a list of "allowed" files, and go from there. For example, someone could upload a file called maliciousScript.jpg.php - it's relatively common for some people to simply explode the "." and check array position 1. It is much better to use strrchr to grab the last extension.
<?php
$filename = 'maliciousScript.jpg.php'; // filename to check $parts = explode('.', $filename); // common (but wrong) method used echo $parts[1]; echo strrchr($filename, '.'); // correct method?>
Now, the second thing you can check is the mime type. The mime type is the embedded "indentifier" for filetypes and is much more reliable than going by extension. There are a few different and sometimes outdated ways to do this using PHP. One of the more reliable and simplest ways on a linux machine is to simply use 'file' from the command line. Of course be very careful of what you pipe directly into the
system() function, see the manual for more info, it's best to use something like
escapeshellarg().
<?php
echo system('file -ib '. $filename);?>There are a few inbuilt options you can use however, for example
getimagesize() can return the mimetype, as does some of the new
fileinfo functions. The mime type in getimagesize is stored in 'mime', and can be accessed as shown below.
<?php
$parts = getimagesize($filename);
echo $parts['mime']; ?>
I mentioned before holding your "safe" mimetypes in an array, here's how that would work using what we've learned.
<?php
$parts = getimagesize($filename);
$allowedMimes = array('image/jpg', 'image/png', 'image/gif');
if(in_array($parts['mime'], $allowedMimes))
echo 'Valid Mimetype!'; ?>There are a few tips to hopefully help figure out what a user is uploading and how to deal with it, if you have any other tips feel free to comment.
#1 Daniel15 says:
I was looking for an easy way to do this, and those fileinfo functions will definitely help me! Thanks! :D