使用php来检查通过表单上传的文件的MIME类型 [英] Using php to check MIME type of file uploaded via form

查看:146
本文介绍了使用php来检查通过表单上传的文件的MIME类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我创建了一个网站,让用户可以将要扫描的csv文件上传到mySQL数据库。因为我不想冒险的人上传奇怪的文件,可以搅乱我的数据库我猜这是一个好主意,检查文件的MIME类型。从其他线程我已经明白,正确做到这一点的唯一方法是使用finfo()。但是我没有得到它的工作。在我的uploadfile.php中的下面的代码只是打印出临时文件名称,后面跟着hello。

  $ filename = $ _FILES [ 文件] [ temp_name]; 
echo $ filename;
$ b $ if(function_exists('finfo_open')&& $ mode == 0){
$ finfo = finfo_open(FILEINFO_MIME_TYPE);
echo finfo_file($ finfo,$ filename);
finfo_close($ finfo);
回声hello;





$ b所以我知道文件已经正确上传了,我知道函数存在,我知道if子句中没有错误。那么为什么不行呢?
我正在通过MAMP测试这个,并且正在考虑那里可能有一些错误?虽然它有PHP 5.4.4版。



我也尝试了不同的版本,如:

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

但没有任何效果。它永远不会打印任何MIME类型:(我能做些什么来解决这个问题?

解决方案

finfo_file可以并将返回空字符串和FALSE如果找不到类型的话。



mime类型的问题在于,你也不能相信它们。

我之前做了这个,用fgetcsv解析了这些文件,发现有任何错误,我放弃了这个文件,这样你就可以确定它是有效的csv。



插入你的数据库,确保你做了正确的转义或使用准备好的语句。


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?

解决方案

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.

这篇关于使用php来检查通过表单上传的文件的MIME类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆