Photograph of a Spanish lighthouse at dusk

To gain access to image metadata, you must load the file a server-side language. You can dynamically load the image in any way you please, including the methods I’ve shown in the past: the only condition is that PHP must be able to address the image file. Here, to make things clearer, I’ll use the image’s filename directly, rather than using a variable.

From PHP’s perspective, IPTC metatags are secreted in the getimagesize function. To make this information visible, we’ll create an array, fill it with getimagesize data, and then use print_r to make the keys of the array visible (I’ll wrap the print_r in a <pre> to format the array in a more presentable fashion:

<?php $picinfo = array();
getimagesize('lighthouse_spain.jpg', $picinfo);
echo "<pre>";
print_r(array_keys($picinfo));
echo "</pre>"; ?>

The result of our print_r will be somewhat obfuscated:

Array (
	[0] => APP1
	[1] => APP12
	[2] => APP13
	[3] => APP14
)

What you need to know is that the ITPC information lies within that third slot. “APP13” is an array unto itself; we could see its contents by using the itpcparse function, and then printing the results out:

if(isset($picinfo['APP13'])) {
	$iptc = iptcparse($picinfo['APP13']);
	print_r($iptc);
}

Now we’re getting somewhere. I’ll show just the relevant parts of the array:

Array (
[2#105] => Array
   ([0] => Lighthouse at dusk in Asturias, Spain)
[2#080] => Array
   ([0] => René González) 
[2#055] => Array
   ([0] => 20111016)
[2#090] => Array
   ([0] => Asturias) 
[2#101] => Array
   ([0] => Spain)
)

This matches the metadata entered into the image in PhotoShop. Now we just need some PHP to extract it and put the results into variables, with a little help from the substr(), date, and mktime() functions:

if(isset($picinfo['APP13'])) {
$iptc = iptcparse($picinfo["APP13"]);
if (is_array($iptc)) { 
	$description = $iptc['2#105'][0];
   	$time = $iptc['2#055'][0];
   	$year = substr($time, 0, 4);
	$month = substr($time, 4, 2);
 	$day = substr($time, -2);
 	$datetaken = date('l F jS Y', mktime(0, 0, 0, $month, $day, $year));
 	$city = $iptc["2#090"][0];
 	$country = $iptc["2#101"][0];
 	$creator = $iptc["2#080"][0];
}

Now we can caption any image read this way with the following information. (Here I’ve gone back to assuming we can address the image itself with a variable.)

<figure>
	<img src="<?=$image?>px;" alt="<?=$description?>" >
	<figcaption>
		<?=$description?>. Taken by <?=$creator?> on <?=$datetaken?>
	</figcaption>
</figure>

Want To Go Further?

Full CMS systems such as ZenPhoto have this same functionality, but if you only need to create captions for a few dozen images while retaining greater control of your site, I’d suggest this technique is the route to go.

Photograph by John Finn, shared under a Creative Commons license

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.