PHP – exif_imagetype() function

The EXIF (Exchangeable image file format) PHP extension enables you to work with metadata from images taken by digital devices like digital cameras and cell phones. The exif_imagetype() function determines the type of an image by reading its first bytes and checking its signature. This is useful for validating file types before processing or checking browser compatibility.

Syntax

int exif_imagetype(string $filename)

Parameters

The function accepts a single parameter:

  • $filename − Path to the image file to check

Return Value

Returns an integer constant representing the image type when a valid signature is found, or false on failure.

Imagetype Constants

Value Constant Value Constant
1 IMAGETYPE_GIF 10 IMAGETYPE_JP2
2 IMAGETYPE_JPEG 11 IMAGETYPE_JPX
3 IMAGETYPE_PNG 12 IMAGETYPE_JB2
4 IMAGETYPE_SWF 13 IMAGETYPE_SWC
5 IMAGETYPE_PSD 14 IMAGETYPE_IFF
6 IMAGETYPE_BMP 15 IMAGETYPE_WBMP
7 IMAGETYPE_TIFF_II 16 IMAGETYPE_XBM
8 IMAGETYPE_TIFF_MM 17 IMAGETYPE_ICO
9 IMAGETYPE_JPC 18 IMAGETYPE_WEBP

Example 1: Detecting JPEG Image

This example demonstrates detecting a JPEG image type ?

<?php
   // Check image type
   $filetype = exif_imagetype('images/sample.jpg');
   
   if ($filetype !== false) {
       echo "The file type is: " . $filetype;
       echo "\nImage type constant: " . ($filetype === IMAGETYPE_JPEG ? 'IMAGETYPE_JPEG' : 'Other');
   } else {
       echo "Unable to determine image type";
   }
?>
The file type is: 2
Image type constant: IMAGETYPE_JPEG

Example 2: Detecting PNG Image

This example shows detection of a PNG image type ?

<?php
   // Check PNG image type
   $filetype = exif_imagetype('images/sample.png');
   
   if ($filetype !== false) {
       echo "The file type is: " . $filetype;
       echo "\nImage type constant: " . ($filetype === IMAGETYPE_PNG ? 'IMAGETYPE_PNG' : 'Other');
   } else {
       echo "Unable to determine image type";
   }
?>
The file type is: 3
Image type constant: IMAGETYPE_PNG

Practical Usage

Common use case for validating uploaded files ?

<?php
   function validateImageType($filename) {
       $allowedTypes = [IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF];
       $imageType = exif_imagetype($filename);
       
       if ($imageType === false) {
           return false;
       }
       
       return in_array($imageType, $allowedTypes);
   }
   
   // Usage
   if (validateImageType('upload.jpg')) {
       echo "Valid image file";
   } else {
       echo "Invalid image file";
   }
?>

Conclusion

The exif_imagetype() function provides a reliable way to detect image file types by examining file signatures rather than relying on file extensions. It's essential for validating uploads and ensuring compatibility with image processing functions.

Updated on: 2026-03-15T10:03:01+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements