What is the best way to determine if a file is an image in PHP?

advertisements

I have a sever which people can upload files to. The problem is that some of the filenames are mangled (dont have any extension) and so I cannot immediately determine file type. This question is two part: for the files which do have filenames what is the best way to determine whether or not it is an image? (Just a big long if/else if list?) Secondly, for the files which dont have extensions, how can I determine if they are images?


You can use exif_imagetype()

<?php
    $type =exif_imagetype($image);

where $type is a value

  1. IMAGETYPE_GIF
  2. IMAGETYPE_JPEG
  3. IMAGETYPE_PNG
  4. IMAGETYPE_SWF
  5. IMAGETYPE_PSD
  6. IMAGETYPE_BMP
  7. IMAGETYPE_TIFF_II (intel byte order)
  8. IMAGETYPE_TIFF_MM (motorola byte order)
  9. IMAGETYPE_JPC
  10. IMAGETYPE_JP2
  11. IMAGETYPE_JPX
  12. IMAGETYPE_JB2
  13. IMAGETYPE_SWC
  14. IMAGETYPE_IFF
  15. IMAGETYPE_WBMP
  16. IMAGETYPE_XBM
  17. IMAGETYPE_ICO

From the manual:

When a correct signature is found, the appropriate constant value will be returned otherwise the return value is FALSE. The return value is the same value that getimagesize() returns in index 2 but exif_imagetype() is much faster.