php 如何使用 getimagesize() 检查上传时的图像类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12761445/
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
php how to use getimagesize() to check image type on upload
提问by neeko
Possible Duplicate:
GetImageSize() not returning FALSE when it should
i currently have a filter system as follows:
我目前有一个过滤系统如下:
// Check to see if the type of file uploaded is a valid image type
function is_valid_type($file)
{
// This is an array that holds all the valid image MIME types
$valid_types = array("image/jpg", "image/JPG", "image/jpeg", "image/bmp", "image/gif", "image/png");
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
but i have been told that it is better to check the filetype myself, how would i use the getimagesize() to check the filetype in a similar way?
但有人告诉我最好自己检查文件类型,我将如何使用 getimagesize() 以类似的方式检查文件类型?
回答by user1704650
getimagesize()returns an array with 7 elements. The index 2 of the array contains one of the IMAGETYPE_XXXconstants indicating the type of the image.
getimagesize()返回一个包含 7 个元素的数组。数组的索引 2 包含IMAGETYPE_XXX指示图像类型的常量之一。
The equivalent of the function provided using getimagesize() would be
使用 getimagesize() 提供的函数的等价物将是
function is_valid_type($file)
{
$size = getimagesize($file);
if(!$size) {
return 0;
}
$valid_types = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP);
if(in_array($size[2], ?$valid_types)) {
return 1;
} else {
return 0;
}
}
回答by GBD
You can use as below
您可以使用如下
$img_info = getimagesize($_FILES['image']['tmp_name']);
$mime = $img_info['mime']; // mime-type as string for ex. "image/jpeg" etc.
回答by Niet the Dark Absol
Firstly check if getimagesizereturns false. If it does, then the file is not a recognised image format (or not an image at all).
首先检查是否getimagesize返回false。如果是,则该文件不是可识别的图像格式(或根本不是图像)。
Otherwise, get index 2 of the returned array and run it through image_type_to_mime_type. This will return a string like "image/gif" etc. See the docsfor more info.
否则,获取返回数组的索引 2 并运行它image_type_to_mime_type。这将返回一个字符串,如“image/gif”等。有关更多信息,请参阅文档。

