检查上传文件的最可靠方法是图像 [英] the most reliable way to check upload file is an image
问题描述
我想验证上传的文件是否是图像.搜索后,我发现了两种方法,我认为这是一种很好的方法.第一个代码是:
I want to validate my upload files is it an images or not. after searching i found two way that i think is a good way to do it. the first code is:
$whitelist_type = array('image/jpeg', 'image/png','image/gif');
$fileinfo = finfo_open(FILEINFO_MIME_TYPE);
if (!in_array(finfo_file($fileinfo, $file['tmp_name']), $whitelist_type)) {
$error[] = "Uploaded file is not a valid image";
}
和第二个代码:
if (!getimagesize($_FILES['photo']['tmp_name'])) {
$error[] = "Uploaded file is not a valid image";
}
哪个代码更可靠地检查它是图像,为什么?还是比这更好的方法?谢谢.
which code is more reliable to check that it's an images and why? or is it any better way than this? thanks.
推荐答案
finfo_*
库会很好,但是它将与> = 5.3.0
版本
finfo_*
library would be good but it will work with >= 5.3.0
versions,
AND getimagesize()
GD
库函数,返回图像信息WxH
和size
AND getimagesize()
GD
library function that is return image info WxH
and size
如果图像无效,则getimagesize()
显示警告,因此最好使用finfo_*
函数来验证图像
if image invalid then getimagesize()
show warning so better to use to validate image using finfo_*
function,
您也可以使用跨版本代码,请参见下面的示例代码
you can also do for cross version code, see below sample code
<?php
$file = $_FILES['photo'];
$whitelist_type = array('image/jpeg', 'image/png','image/gif');
$error = null;
if(function_exists('finfo_open')){ //(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)
$fileinfo = finfo_open(FILEINFO_MIME_TYPE);
if (!in_array(finfo_file($fileinfo, $file['tmp_name']), $whitelist_type)) {
$error[] = "Uploaded file is not a valid image";
}
}else if(function_exists('mime_content_type')){ //supported (PHP 4 >= 4.3.0, PHP 5)
if (!in_array(mime_content_type($file['tmp_name']), $whitelist_type)) {
$error[] = "Uploaded file is not a valid image";
}
}else{
if (!@getimagesize($file['tmp_name'])) { //@ - for hide warning when image not valid
$error[] = "Uploaded file is not a valid image";
}
}
这篇关于检查上传文件的最可靠方法是图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!