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";
}
and the second code:
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.
PHP: Check (validate) if the Uploaded File is an Image. In this tutorial I will show you how to create an image validator script. You can choose between 2 methods of validation: one that will verify if the file is actually an image, by checking the file’s mime-type, and the other one which checks the extension of the uploaded file.
You can choose between 2 methods of validation: one that will verify if the file is actually an image, by checking the file’s mime-type, and the other one which checks the extension of the uploaded file.
If the file is validated the user will see a successful submission message and the file will be moved in the specified image folder. The uploaded file failed to pass the validation process?
If $file_info is empty, then the uploaded file is not an image. We will detect the image’s mime type and we will use this information to add the correct extension to the file. // Check for a correct extension.
finfo_*
library would be good but it will work with >= 5.3.0
versions,
AND getimagesize()
GD
library function that is return image info WxH
and size
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";
}
}
Why not use exif_imagetype:
if (exif_imagetype($file['tmp_name']) != (IMAGETYPE_JPEG || IMAGETYPE_GIF || IMAGETYPE_PNG)) {
$error[] = "Uploaded file is not a valid image";
}
It's probably going to be faster than any of the others. (PHP 4 >= 4.3.0, PHP 5)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With