Get Image Metadata in PHP

- 1 minute read

This PHP function will grab the width, height, and MIME type of a given image:

function getMetadata($path) {
    if (!realpath($path)) $path = $_SERVER['DOCUMENT_ROOT'].$path;
    return getimagesize($path);
}

To use it, just pass a path to the getMetadata function, such as /path/to/apple.jpg:

$metadata = $getMetadata('/path/to/apple.jpg');

$width = $metadata[0]; // Returns the integer width, in pixels
$height = $metadata[1]; // Returns the integer height, in pixels,
$mimeType = $metadata['mime']; // Returns the MIME type as a string

If this snippet doesn’t work, try uncommenting these two lines in your php.ini configuration file:

;extension=php_mbstring.dll
;extension=php_exif.dll

You can uncomment lines by removing the semicolon that precedes them.

Link to this section Getting image EXIF headers in PHP

This modified getMetadata function returns the EXIF metadata of a given image file:

function getMetadata($path) {
    if (!realpath($path)) $path = $_SERVER['DOCUMENT_ROOT'].$path;
    return exif_read_data($path);
}

Passing an image file path to the above snippet will return an associative array, where each key is a header and each value is the associated header value.

However, if there are no headers, it will return false.

Link to this section Conclusion

I hope you found one of these snippets useful!

And if you’re having issues, just remember to uncomment those two lines in your configuration file. Don’t forget to restart your server afterwards!

Thanks for reading.