What is the best and fastest way to check if the image is valid in PHP ? I need it to be able to check GIF, JPG as well as PNG images.
exif_imagetype is a better solution.
This method is faster than using getimagesize. To quote php.net "The return value is the same value that getimagesize() returns in index 2 but exif_imagetype() is much faster."
if(exif_imagetype('path/to/image.jpg')) {
// your image is valid
}
Update:
After reading that getimagesize can be unreliable I tried to find some more info on what file types can give false positives but could not find any more info so performed a brief test (using exif_imagetype
):
PowerPoint-survey-results.pptx - N
LRMonoPhase4.wav - N
TestWordDoc.doc - N
drop.avi - N
test.dll - N
raw_data_sample.sav - N
text.txt - N
Excel-survey-results.xlsx - N
pdf-test.pdf - N
simplepie-1.5.zip - N
Word-survey-results.docx - N
centaur_1.mpg - N
Test.svg - N
multipage_tif_example.tif - Y
200.gif - Y
Test.png - Y
test.jpg - Y
I realise this is not exhaustive however at least show that with common file types the results are as expected.
As recommended by the PHP documentation:
"Do not use getimagesize() to check that a given file is a valid image.Use a purpose-built solution such as the Fileinfo extension instead."
Here is an example:
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$type = finfo_file($finfo, "test.jpg");
if (isset($type) && in_array($type, array("image/png", "image/jpeg", "image/gif"))) {
echo 'This is an image file';
} else {
echo 'Not an image :(';
}
exif_imagetype is much faster than getimagesize and doesn't use gd-Lib (leaving a leaner mem footprint)
function isImage($pathToFile)
{
if( false === exif_imagetype($pathToFile) )
return FALSE;
return TRUE;
}
I use this function... it checks urls too
function isImage($url){
$params = array('http' => array(
'method' => 'HEAD'
));
$ctx = stream_context_create($params);
$fp = @fopen($url, 'rb', false, $ctx);
if (!$fp)
return false; // Problem with url
$meta = stream_get_meta_data($fp);
if ($meta === false){
fclose($fp);
return false; // Problem reading data from url
}
}
I guess getimagesize:
list($width, $height, $type, $attr) = getimagesize("path/to/image.jpg");
if (isset($type) && in_array($type, array(
IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF))) {
...
}
I use this:
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;
}