Using php to check MIME type of file uploaded via form

匆匆过客 提交于 2019-12-11 03:33:55

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/24181201/using-php-to-check-mime-type-of-file-uploaded-via-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!