Eko*_*Eko 3 php file-upload file-type image mime-types
我想验证我的上传文件是否是图像。搜索后,我发现了两种我认为是一种好的方法。第一个代码是:
$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";
}
Run Code Online (Sandbox Code Playgroud)
第二个代码:
if (!getimagesize($_FILES['photo']['tmp_name'])) {
$error[] = "Uploaded file is not a valid image";
}
Run Code Online (Sandbox Code Playgroud)
哪个代码更可靠地检查它是图像,为什么?还是比这更好的方法?谢谢。
finfo_* 库会很好,但它将与> =一起使用 5.3.0版本,
AND getimagesize() GD库函数返回图像信息,WxH然后size
如果图片无效,则getimagesize()显示警告,因此最好使用finfo_*功能来验证图片,
您也可以使用跨版本代码,请参见下面的示例代码
<?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";
}
}
Run Code Online (Sandbox Code Playgroud)