Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best and fastest way to check if the image is valid in PHP?

Tags:

php

image

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.

like image 202
chubbyk Avatar asked Sep 12 '11 20:09

chubbyk


People also ask

How to check URL is image or not in PHP?

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).

How can I get image type in PHP?

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.


1 Answers

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.

like image 161
Felix Eve Avatar answered Sep 30 '22 08:09

Felix Eve