dqgo99177 2012-05-18 16:21
浏览 67
已采纳

如何使用finfo来确定多种文件类型?

I am trying to use finfo to determine if the file is an image file before uploading it into the server. My question though is that the code below is only for jpeg, but I have other file types as well to allow. So I have 2 questions:

Question 1:

How can I use finfo to check for multiple file types such as gif, tiff, png, ico etc.

Question 2: Do I need to use other validation methods to check to see if the is an image or is I what I got below be enough?

Below is code:

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimetype = image_type_to_mime_type(exif_imagetype('/path/to/file.jpg'));

if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/tiff")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/bmp")
|| ($_FILES["file"]["type"] == "image/ico")

{

   if ($finfo !== FALSE){

    move_uploaded_file($_FILES["fileImage"]["tmp_name"],
    "ImageFiles/" . $_FILES["fileImage"]["name"]);
    $result = 1;

   @finfo_close($finfo);
}
}
  • 写回答

1条回答 默认 最新

  • douling8772 2012-05-18 17:20
    关注

    This should work to check whether the file type is an image:

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mimetype = finfo_file($finfo, '/path/to/file.jpg';
    finfo_close($finfo);
    
    if (substr ($mimetype, 0, 5) == 'image') {
        // its an image
    }
    else {
        // its not an image!
    }
    

    Second option, if you're using PHP 5.2 or lower:

    $mimetype = mime_content_type('/path/to/file.jpg';
    
    if (substr ($mimetype, 0, 5) == 'image') {
        // its an image
    }
    else {
        // its not an image!
    }
    

    As for other validation methods, you should use the getimagesize() function: http://php.net/manual/en/function.getimagesize.php

    if (getimagesize ('/path/to/file.jpg')) {
        // its an image
    }
    else {
        // its not an image!
    }
    

    This way your script can't be fooled by changing the mime type or extension of a file.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示