My question is simple:
What is the best (and secure) way to check image type?
I need it for my website, where I want to upload photos. (allowed extension jpeg, png, gif? )
Thank you ...
My question is simple:
What is the best (and secure) way to check image type?
I need it for my website, where I want to upload photos. (allowed extension jpeg, png, gif? )
Thank you ...
<?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
echo 'The picture is not a gif';
}
?>
See here for a list of possible types
For your requirements, you will have to use the following
IMAGETYPE_GIF
IMAGETYPE_JPEG
IMAGETYPE_PNG
How is it secure?
Because it doesn't only check for extension to declare something innocent. It actually does this
exif_imagetype() reads the first bytes of an image and checks its signature. When a correct signature is found, the appropriate constant value will be returned otherwise the return value is FALSE.
You could also use regex like so :
if( preg_match('/\.(jpg|jpeg|png|gif)(?:[\?\#].*)?$/i', $image, $matches) ) {
//Your code here
}
$filetype = pathinfo('yourimage.png', PATHINFO_EXTENSION);
if($filetype == "jpeg" || $filetype == "jpg" || $filetype == "png" || $filetype == "gif"){
echo "Yay, correct filetype!";
}