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

时间:2012-05-18 16:21:33

标签: php file-upload

我试图在将文件上传到服务器之前使用finfo来确定文件是否是图像文件。我的问题是,下面的代码仅适用于jpeg,但我也有其他文件类型允许。所以我有两个问题:

问题1:

如何使用finfo检查多种文件类型,例如gif,tiff,png,ico等。

问题2:我是否需要使用其他验证方法来检查图像是否是图像,或者我下面的内容是否足够?

以下是代码:

$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 个答案:

答案 0 :(得分:0)

这应该可以检查文件类型是否为图像:

$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!
}

第二个选项,如果您使用的是PHP 5.2或更低版本:

$mimetype = mime_content_type('/path/to/file.jpg';

if (substr ($mimetype, 0, 5) == 'image') {
    // its an image
}
else {
    // its not an image!
}

对于其他验证方法,您应该使用getimagesize()函数:http://php.net/manual/en/function.getimagesize.php

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

这样,您的脚本就不会被更改mime类型或文件扩展名所欺骗。