检查文件是否为图像

检查文件是否为图像

本文介绍了PHP 检查文件是否为图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法确保接收到的文件是 PHP 中的图像?

Is there a way to make sure a received file is an image in PHP?

测试扩展对我来说听起来不太安全,因为您可以上传 script 并将其扩展更改为您想要的任何内容.

Testing for the extension doesn't sound very secure to me as you could upload a script and change its extension to whatever you want.

我也尝试使用 getimagesize,但可能有更适合该特定问题的方法.

I've tried to use getimagesize too, but there might be something more suited for that particular problem.

推荐答案

本地获取 mimetype 的方法:

Native way to get the mimetype:

对于 PHP <5.3 使用mime_content_type()
对于 PHP >= 5.3 使用 finfo_open()mime_content_type()

For PHP < 5.3 use mime_content_type()
For PHP >= 5.3 use finfo_open() or mime_content_type()

获取 MimeType 的替代方法是 exif_imagetypegetimagesize,但这些依赖于安装了适当的库.此外,他们可能只会返回图像 mimetypes,而不是 magic 中给出的整个列表.mime.

Alternatives to get the MimeType are exif_imagetype and getimagesize, but these rely on having the appropriate libs installed. In addition, they will likely just return image mimetypes, instead of the whole list given in magic.mime.

虽然 mime_content_type 在 PHP 4.3 中可用,并且是 FileInfo 扩展的一部分(自 PHP 5.3 起默认启用,Windows 平台除外,必须手动启用,详情参见 此处).

While mime_content_type is available from PHP 4.3 and is part of the FileInfo extension (which is enabled by default since PHP 5.3, except for Windows platforms, where it must be enabled manually, for details see here).

如果您不想关心系统上可用的内容,只需将所有四个函数包装到一个代理方法中,该方法将函数调用委托给可用的任何内容,例如

If you don't want to bother about what is available on your system, just wrap all four functions into a proxy method that delegates the function call to whatever is available, e.g.

function getMimeType($filename)
{
    $mimetype = false;
    if(function_exists('finfo_open')) {
        // open with FileInfo
    } elseif(function_exists('getimagesize')) {
        // open with GD
    } elseif(function_exists('exif_imagetype')) {
       // open with EXIF
    } elseif(function_exists('mime_content_type')) {
       $mimetype = mime_content_type($filename);
    }
    return $mimetype;
}

这篇关于PHP 检查文件是否为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:53