沃梦达 / 编程问答 / php问题 / 正文

PHP 文件上传:基于 MIME 或扩展名的验证?

PHP file upload: mime or extension based verification?(PHP 文件上传:基于 MIME 或扩展名的验证?)

本文介绍了PHP 文件上传:基于 MIME 或扩展名的验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试处理文件上传时,我应该根据文件 MIME 类型还是文件扩展名运行验证?

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?

在这些日子里,我依赖于 MIME 类型,但在这篇文章中获得最多投票的答案

In these days I was relying on MIME type but the answer with most up-votes in this post

PHP 中的文件上传问题 说:

永远不要依赖浏览器提交的 MIME 类型!

Never rely on the MIME type submitted by the browser!

推荐答案

好的,对于所有在这里大喊螺丝扩展,检查 MIME!FILEINFO RLZ!"的天才,我准备了一些教程:

Okay, so to all the geniouses here yapping something about "SCREW EXTENSIONS, CHECK MIME! FILEINFO RLZ!", I've prepared some tutorial:

  1. 下载这个我画的漂亮的php标志
  2. 查看它.很不错,不是吗?
  3. 将其重命名为whatever_you_like.php
  4. 通过所有精彩的哑剧类型/任何跳棋
  5. 运行它

总而言之,您永远不要永远依赖 MIME 类型.您的网络服务器不关心 MIME 类型,它决定了由 EXTENSION 执行的操作,最终被否决的 @Col.Shrapnel 的回答其实是对的.通过检查 MIME 提供给您的任何信息在执行时绝对与您的网络服务器无关.

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.

打开网站以应对此类攻击的不常见代码如您所愿:

the not-as-uncommon-code-as-you'd-want-it-to-be that opens a website to this type of attack:

<?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!';
}

这篇关于PHP 文件上传:基于 MIME 或扩展名的验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:PHP 文件上传:基于 MIME 或扩展名的验证?

基础教程推荐