PHP check if file is an image

sf89 picture sf89 · Mar 14, 2013 · Viewed 136.6k times · Source

Is there a way to make sure a received file is an image in PHP?

Testing for the extension doesn't sound very secure to me as you could upload a script and change its extension to whatever you want.

I've tried to use getimagesize too, but there might be something more suited for that particular problem.

Answer

George Mickleburgh picture George Mickleburgh · Mar 14, 2013

The getimagesize() should be the most definite way of working out whether the file is an image:

if(@is_array(getimagesize($mediapath))){
    $image = true;
} else {
    $image = false;
}

because this is a sample getimagesize() output:

Array (
[0] => 800
[1] => 450
[2] => 2
[3] => width="800" height="450"
[bits] => 8
[channels] => 3
[mime] => image/jpeg)