0

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 ...

tomascapek
  • 841
  • 1
  • 8
  • 20

3 Answers3

3
<?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.

Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
  • Does getimagesize do the same as exif_image type? – tomascapek Jan 26 '14 at 16:42
  • 1
    According to PHP Manual: `The return value is the same value that getimagesize() returns in index 2 but exif_imagetype() is much faster. ` – Hanky Panky Jan 26 '14 at 16:43
  • 1
    With 14k points you should know better than to answer a question that has been answered before... – DanMan Jan 26 '14 at 16:56
  • Why don't you take my 14k points and then post that same answer which you think this question is duplicate of? That question you linked to, was just terrible. There is not 1 decent answer there that could be called duplicate of this one. Not all programming is string manipulation and checking for regexes if the extensions match. – Hanky Panky Jan 26 '14 at 17:00
0

You could also use regex like so :

if( preg_match('/\.(jpg|jpeg|png|gif)(?:[\?\#].*)?$/i', $image, $matches) ) {
    //Your code here
}
bastienbot
  • 123
  • 1
  • 14
0
$filetype = pathinfo('yourimage.png', PATHINFO_EXTENSION);
if($filetype == "jpeg" || $filetype == "jpg" || $filetype == "png" || $filetype == "gif"){ 
  echo "Yay, correct filetype!";
}
AndiPower
  • 853
  • 10
  • 20