Php – the best and fastest way to check if the image is valid in PHP

imagePHP

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.

Best Answer

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.