【问题标题】:Mime types for uploading pdf in PHP in different browsers用于在不同浏览器中以 PHP 上传 pdf 的 Mime 类型
【发布时间】:2013-12-20 19:04:55
【问题描述】:

我正在创建一个允许用户上传 pdf 文档的 Web 应用程序。以下是检查(限制)文档类型为 pdf 的代码。

if (isset($_POST['submitbutton'])) {
  $name = $_FILES['myfile']['name'];
  $type = $_FILES['myfile']['type'];
  $size = $_FILES['myfile']['size'];
  $tmpname = $_FILES['myfile']['tmp_name'];
  $ext = substr($name, strrpos($name,'.'));  //Get the extension of the selected file
  echo $type.' This is the type';
  echo '<br>';
  if (($type == "application/pdf")||($type == "application/octet-streamn")) {
    echo 'ok';
  } else {
    echo "That is not a pdf document";
  }
}

我通过 echo(ing) $type 到屏幕来检查类型。但是Firefox的类型输出不同。我只需要确认以下 MIME 类型。我说的对吗:

Internet Explorer:应用程序/pdf

Opera:应用程序/pdf

FireFox:应用程序/八位字节流

或者是否有涵盖所有现有浏览器的标准 mime 类型。请帮忙,我的提要仍然被 php 和文件弄湿了

【问题讨论】:

  • 如果依赖 mime 类型,您将无法知道文件的真正含义。任何人都可以发送一个 .php 文件并伪造它的图像/gif 或类似文件。这就是为什么我们不信任用户输入,文件上传是用户输入。
  • 不要相信用户发送的任何内容。发送 mime 类型为 application/pdf 的 PHP 文件将非常简单。
  • 如果我使用 application/pdf 仅用于检查文件类型,我得到的输出表明它不是 firefox 上的 pdf。有解决办法吗?因为我认为我不能排除在 firefox 上检查 pdf 的文件

标签: php pdf file-upload


【解决方案1】:

不要相信$_FILES['myfile']['type'],因为它是由客户提供的。更好的解决方案是使用finfo_open:

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$type = finfo_file($finfo, $_FILES['myfile']['tmp_name']);
if($type == 'application/pdf'){
    //Is a PDF
}

【讨论】:

    【解决方案2】:

    为避免混淆和浏览器问题,请使用 JQuery

    var filename="";
    $('#upload').on( 'change', function() {
    filename= $( this ).val();
    var exten = filename.split('.').pop();
    if(exten!="pdf"){
        alert("Only pdf documents are allowed");
        $(this).val('');
    }
    });
    

    【讨论】:

      猜你喜欢
      • 2013-01-05
      • 2017-04-20
      • 2011-10-06
      • 2015-10-22
      • 2013-08-23
      • 2010-11-12
      • 2015-03-12
      相关资源
      最近更新 更多