如何检查在PHP中上传的文件类型 [英] How to check uploaded file type in PHP

查看:97
本文介绍了如何检查在PHP中上传的文件类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用这段代码来检查图像的类型,

  $ f_type = $ _ FILES ['fupload'] [ '类型']; 

或$ f_type ==image / jpegOR $ f_type ==image / JPEG $ f_type ==image / PNGOR $ f_type ==image / GIF)
{
$ error = False;
}
else
{
$ error = True;

$ / code>

但是有些用户抱怨上传任何类型的图片时会出错一些其他人不会得到任何错误!

我想知道这是否解决了这个问题:

if(mime_content_type($ _FILES ['fupload'] ['type'])==image / gif){...



有什么意见?

解决方案

切勿使用 $ _ FILES .. ['type'] 。其中包含的信息根本没有验证,这是一个用户定义的值。自己测试类型。对于图片, exif_imagetype 通常是一个不错的选择:
$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $'$'$'$'
$ detectedType = exif_imagetype($ _ FILES ['fupload'] ['tmp_name']);
$ error =!in_array($ detectedType,$ allowedTypes);

或者, finfo functions 非常好,如果你的服务器支持的话。


I used this code to check for the type of images,

$f_type=$_FILES['fupload']['type'];

if ($f_type== "image/gif" OR $f_type== "image/png" OR $f_type== "image/jpeg" OR $f_type== "image/JPEG" OR $f_type== "image/PNG" OR $f_type== "image/GIF")
{
    $error=False;
}
else
{
    $error=True;
}

but some users complain they get an error while uploading any type of images, while some others don't get any errors!

I was wondering if this fixes the problem:

if (mime_content_type($_FILES['fupload']['type']) == "image/gif"){...

Any comments?

解决方案

Never use $_FILES..['type']. The information contained in it is not verified at all, it's a user-defined value. Test the type yourself. For images, exif_imagetype is usually a good choice:

$allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
$detectedType = exif_imagetype($_FILES['fupload']['tmp_name']);
$error = !in_array($detectedType, $allowedTypes);

Alternatively, the finfo functions are great, if your server supports them.

这篇关于如何检查在PHP中上传的文件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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