php 如何在PHP中检查上传的文件类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6755192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:09:34  来源:igfitidea点击:

How to check uploaded file type in PHP

phpfile-upload

提问by John

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"){...

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

Any comments?

任何意见?

回答by deceze

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_imagetypeis usually a good choice:

永远不要使用$_FILES..['type']. 其中包含的信息根本没有经过验证,它是用户定义的值。自己测试类型。对于图像,exif_imagetype通常是一个不错的选择:

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

Alternatively, the finfofunctionsare great, if your server supports them.

或者,这些finfo功能很棒,如果您的服务器支持它们。

回答by feeela

In addition to @deceze, you may also finfo()to check the MIME-type of non-image-files:

除了@deceze,您还可以使用finfo()来检查非图像文件的 MIME 类型:

$finfo = new finfo();
$fileMimeType = $finfo->file($path . $filename, FILEINFO_MIME_TYPE);

回答by Violence

Sure you could check if it's an image with exif, but a better way I think is to do with finfo like this:

当然你可以用exif检查它是否是一个图像,但我认为更好的方法是像这样使用finfo:

$allowed_types = array ( 'application/pdf', 'image/jpeg', 'image/png' );
$fileInfo = finfo_open(FILEINFO_MIME_TYPE);
$detected_type = finfo_file( $fileInfo, $_FILES['datei']['tmp_name'] );
if ( !in_array($detected_type, $allowed_types) ) {
    die ( 'Please upload a pdf or an image ' );
}
finfo_close( $fileInfo );

回答by Picard

The best way in my opinion is first to use getimagesize()followed by imagecreatefromstring().

我认为最好的方法是首先使用getimagesize() ,然后使用imagecreatefromstring()

    $size = getimagesize($filename);
    if ($size === false) {
        throw new Exception("{$filename}: Invalid image.");
    }
    if ($size[0] > 2500 || $size[1] > 2500) {
        throw new Exception("{$filename}: Image too large.");
    }

    if (!$img = @imagecreatefromstring(file_get_contents($filename))) {
        throw new Exception("{$filename}: Invalid image content.");
    }

Checking by getimagesize()prevents some DoS attacks, because we don't have to try to imagecreatefromstring()from every file provided by the user, either non-image file or file too big. Unfortunately, according to PHP docscannot be relied on for checking image type content.

Check bygetimagesize()可以防止一些 DoS 攻击,因为我们不必尝试imagecreatefromstring()从用户提供的每个文件,无论是非图像文件还是文件太大。不幸的是,根据PHP 文档不能依赖于检查图像类型内容。

The imagecreatefromstring()finally tries to open the file as an image - if is succeeds - we have an image.

imagecreatefromstring()最后尝试打开该文件作为图像-如果成功-我们有一个形象。

回答by Salvi Pascual

This is a simple, one line script that I use often.

这是我经常使用的一个简单的单行脚本。

$image = "/var/www/Core/temp/image.jpg";
$isImage = explode("/", mime_content_type())[0] == "image";

Basically I am using mime_content_type() to get something like "image/jpg" and then exploding it by "/" and checking against the first element of the array to see if it says "image".

基本上,我使用 mime_content_type() 来获取类似“image/jpg”的内容,然后通过“/”将其分解并检查数组的第一个元素以查看它是否显示“image”。

I hope it works!

我希望它有效!

回答by aesede

In PHP 5.5 I use this function for getting file type and check if image:

在 PHP 5.5 中,我使用此函数获取文件类型并检查图像:

function getFileType( $file ) {
    return image_type_to_mime_type( exif_imagetype( $file ) );
}

// Get file type
$file_type = getFileType( 'path/to/images/test.png' );
echo $file_type;
// Prints image/png
// 1. All images have mime type starting with "image"
// 2. No other non-image mime types contain string "image" in it 

Then you could do:

那么你可以这样做:

if ( strpos( $filetype, 'image' ) !== false ) {
    // This is an image 
}

Complete list of mime types: http://www.sitepoint.com/web-foundations/mime-types-complete-list/

mime 类型的完整列表:http: //www.sitepoint.com/web-foundations/mime-types-complete-list/

回答by Autumn Leonard

That last line is close. You can use: if (mime_content_type($_FILES['fupload']['tmp_name']) == "image/gif"){...

最后一行很接近。您可以使用: if (mime_content_type($_FILES['fupload']['tmp_name']) == "image/gif"){...

In the case I'm currently working on, my $_FILES..['type']reports itself as "text/csv", while both mime_content_type()and finfo()(suggested by others) report "text/plain.". As @deceze points out, $_FILES..['type']is only useful to know what type a client thinks a file is.

在我目前正在处理的情况下,我$_FILES..['type']将自己报告为“text/csv”,而两者mime_content_type()finfo()(其他人建议的)报告为“text/plain.”。正如@deceze 指出的那样,$_FILES..['type']只有了解客户认为文件是什么类型才有用。

回答by Full Dev

you can try this

你可以试试这个

$file_extension = explode('.',$file['name']);
$file_extension = strtolower(end($file_extension));
$accepted_formate = array('jpeg','jpg','png');
if(in_array($file_extension,$accepted_formate)) {           
  echo "This is jpeg/jpg/png file";
} else {
  echo $file_extension.' This is file not allowed !!';
}

回答by uutsav

WARNING: the following answer does not actually check the file type. It only checks the name. It is not suitablefor actual security purposes.

警告:以下答案实际上并未检查文件类型。它只检查名称。它不适合实际的安全目的。

EDIT: Don't Use this methodas it serves no security check. I am leaving this answer here so that no one makes the same mistake like me by trying this.

编辑:不要使用此方法,因为它不提供安全检查。我将这个答案留在这里,以便没有人通过尝试这样做而犯同样的错误。



I tried the following and it worked for me:

我尝试了以下方法,它对我有用:

$allowed =  array('gif','png' ,'jpg', 'pdf');
$filename = $_FILES['input_tag_name']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) ) {
    echo 'error';
}

Source link

源码链接