Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to determine whether or not a file is an image in PHP?

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?

like image 683
chacham15 Avatar asked Nov 25 '25 12:11

chacham15


2 Answers

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.

like image 86
macjohn Avatar answered Nov 28 '25 01:11

macjohn


You can use getimagesize It does not require the GD image library and it returns same information about image type. https://www.php.net/manual/en/function.getimagesize.php

like image 38
InuYaksa Avatar answered Nov 28 '25 02:11

InuYaksa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!