Search code examples
phpfile-uploadmime-typesmime

Using php to check MIME type of file uploaded via form


Ok, so I'm creating a website that will let users upload csv-files that are to be scanned in to a mySQL-databse. Because I don't want to risk evil people uploading strange files that can mess with my database I'm guessing it's a good idea to check the mime type of the file. From other threads I've understood that the only way to properly do this is by using finfo(). But I don't get it to work. The following code in my uploadfile.php just prints out the temporary file name followed by "hello".

$filename = $_FILES["file"]["temp_name"];
echo $filename;

if (function_exists('finfo_open')&&$mode==0) {
$finfo = finfo_open(FILEINFO_MIME_TYPE); 
echo finfo_file($finfo,$filename);
finfo_close($finfo); 
echo "hello";
}

So I know that the file has uploaded correctly, I know the function exists, I know that there is no error throughout the if clause. So then why won't it work? I'm testing this through MAMP, and am thinking that maybe there is some error there? Though it has PHP Version 5.4.4.

I have also tried different versions like:

$mimetype = finfo_file($finfo,$filename); 
echo $mimetype;

But nothing works. It never prints any mime type :( What can I do to fix this?


Solution

  • finfo_file can and will return empty string and FALSE if the type is not found.

    Problem with mime types here is, you can't trust them either.

    I did this before and parsed the files with fgetcsv. Any error there and I discarded the file. This way you can be sure it was valid csv.

    When you insert into your database make sure you do the proper escaping or use prepared statements.