Current Location: Home> Latest Articles> PHP Tutorial: Extracting Photo Focal Length Using Exif Extension

PHP Tutorial: Extracting Photo Focal Length Using Exif Extension

M66 2025-11-03

Introduction

With the popularity of digital photography, the number of photos being taken is constantly increasing. For photography enthusiasts, understanding photo metadata is very important. This article will show how to use PHP and the Exif extension to extract the focal length of photos, helping you better understand your images.

What is Exif Data?

Exchangeable Image File Format (Exif) is a file format for storing metadata in digital photos. It records shooting parameters and environmental information, such as focal length, ISO, and shutter speed. PHP's Exif extension provides functions to easily process and extract this data.

Installing and Configuring the Exif Extension

Before using the Exif extension, make sure it is installed in PHP. You can check with the following command:

php -m | grep exif

If 'exif' appears in the output, the extension is installed. If not, you can install it using the steps below:

Run the following command in the terminal:

sudo apt-get install php-exif

Edit the php.ini file:

sudo nano /etc/php/7.4/cli/php.ini

Find the following line and uncomment it:

;extension=exif

Save and exit, then restart PHP:

sudo service php7.4-fpm restart

Extracting Photo Focal Length

Create a PHP script, for example exif_example.php, and place the photo in the same directory. Use the exif_read_data() function to read the photo's Exif data:

<?php
$filename = 'example.jpg'; // Photo file name
$exif_data = exif_read_data($filename, 0, true);
?>

Check if the focal length exists and display it:

<?php
if (isset($exif_data['EXIF']['FocalLength'])) {
 $focal_length = $exif_data['EXIF']['FocalLength'];
 echo "Photo focal length: {$focal_length}mm";
} else {
 echo "Could not retrieve the photo's focal length.";
}
?>

Running and Testing

After saving the script, run it in the terminal:

php exif_example.php

If the photo contains focal length information, the output will look like:

Photo focal length: 50mm

Otherwise, it will indicate that the focal length could not be retrieved.

Conclusion

Using PHP's Exif extension makes it easy to extract the focal length of photos, though not all photos include this information. Proper error handling should be implemented when processing images. This method allows you to quickly access photo metadata, aiding photography learning and image management.