Secure image upload - validation

Which of the following examples is a proper way to validate image extension?

function fileExtension($filename){
  $path_info = pathinfo($filename);
  return $path_info['extension'];
}
$ext=fileExtension($_FILES['filename']['name']);
$allowedExt = array("jpg","jpeg","png","bmp","gif");
if(!in_array(strtolower($tmp_exp[count($tmp_exp)-1]),$allowed_ext)){
//invalid ext
$allowedExt = array("jpg","jpeg","png","bmp","gif");
$tmp_exp = explode(".",$filename);
if(!in_array(strtolower($tmp_exp[count($tmp_exp)-1]),$allowedExt)){
//invalid ext

Using $_FILES[“uploaded_file”][“type”] for checking.

  1. Using getimagesize and checking index 2 of the returned array. That will guarantee you that it’s actually an image as well, as the file extension can be spoofed.

Thank you, so this could be the final code? I just added !getimagesize($filename)

$allowedExt = array("jpg","jpeg","png","bmp","gif"); 
$tmp_exp = explode(".",$filename); 
if(!getimagesize($filename) || !in_array(strtolower($tmp_exp[count($tmp_exp)-1]),$allowedExt))
//invalid ext

Looks OK, but your code will break if the image name has a dot in it. Also, why do you care what the extension is? As long as it’s an image, everything should be OK.