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.
getimagesize('url'); If it returns an array, it is an image type recognized by PHP, even if the image extension is not in the url (per your second link).
The imagetypes() function is an inbuilt function in PHP which is used to return the image types supported by the PHP inbuilt installed library. Parameters: This function does not accept any parameter.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With