问题描述
当我尝试处理文件上传时,是否应该根据文件MIME类型或文件扩展名运行验证?什么是优点&这两种文件验证方式的缺点?
在这些日子里,我依赖于MIME类型,但是在这篇文章中, 说:
- 下载这个漂亮的php标志我画了
- 查看它。很好,是不是?
- 把它重命名为whatever_you_like.php
- 把所有的真棒mime类型/任何跳棋都放进去 >
- 运行它
总而言之,您永远不应该依靠 MIME类型。您的Web服务器不关心MIME类型,它决定 EXTENSION 执行的操作,最后是 @Col。弹片的答案其实是对的。任何通过检查MIME提供给你的信息绝对与你的web服务器在执行时无关。
编辑:这种非常见的代码就像打开一个网站到这种类型的攻击: When I try to process file upload, should I run verification based on file MIME type or file-extension? What are Pros & cons of these 2 ways of file validating? And, Any other security issues should i be concerned of? In these days I was relying on MIME type but the answer with most up-votes in this post File upload issues in PHP says: Okay, so to all the geniouses here yapping something about "SCREW EXTENSIONS, CHECK MIME! FILEINFO RLZ!", I've prepared some tutorial: In conclusion, you should NEVER EVER EVER rely on MIME type. You web server doesn't care about MIME type, it determines what to do by EXTENSION, the ultimately downvoted @Col. Shrapnel's answer is actually right. Any information provided to you by something checking MIME is absolutely irrelevant to your webserver when it comes to execution. EDIT: the not-as-uncommon-code-as-you'd-want-it-to-be that opens a website to this type of attack: 这篇关于PHP文件上传:MIME或基于扩展的验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
<$ p $ <?php
$ mimetype = mime_content_type($ _ FILES ['file'] ['tmp_name']);
if(in_array($ mimetype,array('image / jpeg','image / gif','image / png'))){
move_uploaded_file($ _ FILES ['file'] ['tmp_name '],'/ whatever / something / imagedir /'。$ _FILES ['file'] ['name']);
回声'OK';
} else {
echo'上传真实图片,混蛋!';
}
<?php
$mimetype = mime_content_type($_FILES['file']['tmp_name']);
if(in_array($mimetype, array('image/jpeg', 'image/gif', 'image/png'))) {
move_uploaded_file($_FILES['file']['tmp_name'], '/whatever/something/imagedir/' . $_FILES['file']['name']);
echo 'OK';
} else {
echo 'Upload a real image, jerk!';
}