PHP检查文件是否是一个图像 [英] PHP check if file is an image

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

问题描述

有没有办法确保收到的文件是 PHP



中的图片。扩展名对我来说听起来不太安全,因为您可以上传脚本,并将其扩展名更改为任何您想要的。



我也尝试过使用 getimagesize ,但是可能有更适合这个特殊问题的东西。

解决方案

获取mimetype的原生方式:

对于PHP< / p> 5.3使用 mime_content_type()

对于PHP> 5.3使用 finfo_fopen()



获取MimeType的替代方法是 exif_imagetype getimagesize ,但这些依赖于安装了适当的库。另外,他们可能只是返回图片mimetypes,而不是 magic .mime
$ b

从PHP5.3中删除 mime_content_type 时,它在该版本下运行正常。 E_STRICT 甚至不会提出有关已被弃用的通知。如果你不想打扰你的系统上可用的东西,只需将所有四个函数包装到一个代理方法中,该代理方法将函数调用委托给任何可用的方法,例如

 函数getMimeType($ filename)
{
$ mimetype = false;
if(function_exists('finfo_fopen')){
//使用FileInfo
打开elseif(function_exists('getimagesize')){
//使用GD $ b $打开bif elseif(function_exists('exif_imagetype')){
//用EXIF
打开} elseif(function_exists('mime_content_type')){
$ mimetype = mime_content_type($ filename);
}
return $ mimetype;
}


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

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.

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

解决方案

Native way to get the mimetype:

For PHP < 5.3 use mime_content_type()
For PHP > 5.3 use finfo_fopen()

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.

While mime_content_type is removed from PHP5.3, it works fine below that version. E_STRICT won't even raise a notice about it being deprecated. 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_fopen')) {
        // 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检查文件是否是一个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆