PHP: Targeted Content Delivery

The basis of this method is to use a server-side browser detect method to determine whether the browser is IE5.5 or IE6.0, which support the Microsoft AlphaImageLoader style filter. The PHP function then returns HTML formatted accordingly.

The browser detector

The basis of this function is described elsewhere. Briefly, it takes the user agent string and parses it for information on the browser that is querying the server. Specifically, it tests for:

<?php $ua = $_SERVER['HTTP_USER_AGENT']; $png = 'alpha'; if (strpos($ua,'MSIE') != false && strpos($ua,'Opera') === false) /* browser claims to be IE and is not Opera */ { if (strpos($ua,'Windows NT 5.2') != false) /* OS is Windows Server 2003 or Mac OS X and browser is Safari or iCab (or other unknown) */ { if (strpos($ua,'.NET CLR') === false) return; /* return $png = 'alpha' */ /* OS probably not Windows Server 2003 */ } $ver = substr($ua,strpos($ua,'MSIE')+5,3); if ($ver >= 5.5 && $ver < 7) { /* the browser is Microsoft IE5.5 or IE6 */ $png = 'msie'; } } ?>

Other PHP functions

After the browser has been determined, the correct HTML must be sent to it. For standards-compliant browsers, this must the standard HTML:

<img src="image.png" width="imagewidth" height="imageheight" alt="alternative text">

In the case of IE5.5 and IE6 it must be an HTML element with no (or transparent) content and the PNG applied as a background image style:

<img src="blank.gif" width="imagewidth" height="imageheight" alt="alternative text" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='image.png')">

Realistically, the AlphaImageLoader filter can be applied to any element that has layout (i.e. dimensions), including DIV, H1, and IMG elements. For the purposes of this exercise I've used IMG elements for two reasons. Firstly, it is semantically correct in terms of how the page is intended to be viewed, and secondly the IMG element can have the usual ALT attribute applied to it for the benefit of visitors who have images turned off in their browser.

Therefore, the function must accept at least two parameters, the image source and alternative text, and format these accordingly into the correct HTML for the browser. The image dimensions will be read directly by PHP, assuming that it's compiled with the GD image library.

<?php function create_png_image($img,$alt) { $size = getimagesize($img); if ($GLOBALS['png'] == 'alpha') { $html = "<img src=\"$img\" $size[3] alt=\"$alt\">"; } else { $html = "<img src=\"blank.gif\" $size[3] alt=\"$alt\" style=\"filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='$img')\">"; } return $html; } ?>

Putting it all together

All that's needed now is to call the function from the point in the HTML where the image is required:

<?php echo create_png_image('image.png','alternative text'); ?>

Pros and cons of this method