【问题标题】:PHP upload image file types problems [duplicate]PHP上传图片文件类型问题[重复]
【发布时间】:2013-12-20 13:29:37
【问题描述】:

我是 php 中的上传功能的新手,但是我有这个:

if( $_FILES[$fileElementName]['type'] !== "image/gif"

                || $_FILES[$fileElementName]['type'] !== "image/jpeg"
                || $_FILES[$fileElementName]['type'] !== "image/jpg"
                || $_FILES[$fileElementName]['type'] !== "image/pjpeg"
                || $_FILES[$fileElementName]['type'] !== "image/x-png"
                || $_FILES[$fileElementName]['type'] !== "image/png"
                || $_FILES[$fileElementName]['type'] == "application/x-rar-compressed"
           ){

                 $error = 'wrong file only :GIF,jpg,png .';
 //    die($_FILES[$fileElementName]['type']);  // also i did die here to check
    }

但它不会工作,即使我上传 jpg,它也会说总是错误的。 我确实死了/var_damp,并且该类型适用于 E.G,一切正常: 我上传了 sds.jpg 并让其给出正确:

image/jpeg

但它会一直说总是错误的文件,为什么?

【问题讨论】:

  • 将您的|| 换成&&。发生的情况是,如果(它不是 gif)或(它不是 jpg)您的陈述是正确的 - 因为您上传的是 jpg,所以 gif 永远是正确的。
  • 更简洁的方法是if (!in_array($_FILES[$fileElementName]['type'], array('image/jpeg','image/jpg','image/png',.....))) {// bad type...}

标签: php


【解决方案1】:

Look here the source

尝试这样更短更好的变体:

 $allowedTypes = array('image/jpeg','image/jpg' ,'image/pjpeg' ,'image/pjpeg', 'image/png', 'application/x-rar-compressed');

$fileType = $_FILES[$fileElementName]['type'];

if(!in_array($fileType, $allowedTypes)) {
    // do whatever you need to say that
    // it is an invalid type eg:
    die('You may only upload jpeg images');
}

【讨论】:

  • 这就像一个魅力,谢谢!
  • 本答案中的代码取自stackoverflow.com/a/5143683
  • 如您所见,我资助了一个答案并对这个问题做出了一点正确,有什么问题?我不明白...
  • 您没有链接到源。如果没有链接到它,它看起来就像你自己写了这个答案,而你没有。
  • 嗯,但我认为他也在搜索,也许他看到了这个但无法实施他的问题。这就是为什么我建议为他做出正确的变体
【解决方案2】:

您应该使用条件 && (and) 而不是 || (OR)

为了避免难以维护的大量语句,我会使用数组。

$allowedtypes = array(
  'image/jpg',
  'image/jpeg',
  //..etc
);

if (! in_array($_FILES[$fileElementName]['type'], $allowedTypes)) {
 // not allowed
} else {
 // allowed
}

【讨论】:

  • 你确定它首先是允许的?我认为你混淆了它的 Noy 允许和另一个是允许的,我使用另一个答案是一样的。顺便说一句,谢谢。
  • @Ravg woops,你是对的,cmets 是错误的方式
猜你喜欢
  • 2014-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-03
  • 1970-01-01
  • 2017-06-30
相关资源
最近更新 更多