I have tried with getimagesize()
, finfo
and getting Mime type function. But I have noticed we can not trust on these function as I observed it's fails in my case for some image files. Do we have any better way to identify a file is image or not.
Use case : I have one file with php code inside it. I have saved this file with some image extension. Now I want to block this file from getting uploaded.
Asked
Active
Viewed 3,944 times
1

Muhammad Hassaan
- 7,296
- 6
- 30
- 50

Harish Yadav
- 19
- 1
- 2
-
Show your code. – Muhammad Hassaan Dec 22 '16 at 05:53
-
http://stackoverflow.com/a/15408176/3476207 – Abhishek Dec 22 '16 at 05:54
-
1Possible duplicate of [uploaded file type check by PHP](http://stackoverflow.com/questions/6755192/uploaded-file-type-check-by-php) – Dec 22 '16 at 05:55
4 Answers
0
Try php's inbuilt method to check image type,
int exif_imagetype ( string $filename )
This method returns false
if file is not a valid image otherwise will return an Integer pointing to the type of image.
Also it throws a notice. So you may do something like this.
if(@exif_imagetype($file)){
//Valid Image
} else {
// Invalid
}

anwerj
- 2,386
- 2
- 17
- 36
-
I tried this but if you save a file contains some script with some image extension then also it's returns valid image – Harish Yadav Dec 23 '16 at 10:22
-
-
looking forward to see what file saved as image extension will return valid image as well. I've tried several forms and it all returns false if it's invalid – Someone Special Oct 20 '18 at 04:11
0
i think you should take a look over the
mime_content_type
or
Fileinfo
of
system("file -bi $uploadedfile")
see more detail view over the below post

Community
- 1
- 1

Anand thakkar
- 479
- 3
- 8
0
You can try this below code:
function is_image($path)
{
$a = getimagesize($path);
$image_type = $a[2];
if(in_array($image_type , array(IMAGETYPE_GIF , IMAGETYPE_JPEG
,IMAGETYPE_PNG , IMAGETYPE_BMP)))
{
return true;
}
return false;
}

Awais Mustafa
- 151
- 2
- 9
0
If your server is running on Linux you should execute file
:
$mime = exec("file $tmpFilePath -z -b --mime-type");
This will define mime type correctly

alvery
- 1,863
- 2
- 15
- 35