Gravatars in PHP

The great thing about publishing a blog through your own CMS is that said CMS can be hacked around and added to at will. Of course the downside is that you have to write the code yourself. Unless someone else decides to publish some useful code for the taking. You’ll find below a snippet of code shows how I’ve implemented gravatars in PHP. How useful you’ll find it is open to question.

Essentially the code displays an image only if a gravatar is available. I didn’t want to display a default image so I check that the returned gravatar has a width greater than 1. If the commenter has also supplied a URL then the gravatar is made to link to it.

$gravatar_code = "";
if ($commenter_email) {
    $gravatar_url = "http://www.gravatar.com/avatar.php?
     gravatar_id=".md5($commenter_email).
     "&size=40&rating=PG";
    $gravatar_dimensions = @getimagesize($gravatar_url);
    $gravatar_width = $gravatar_dimensions[0];
    if ($gravatar_width > 1) {
        $gravatar_code = "<img src='$gravatar_url' alt='".
         $commenter_name.
         "&#8217;s Gravatar' title='".$commenter_name.
         "&#8217;s Gravatar' class='gravatar' />";
        if ($commenter_url) {
            $gravatar_code = "<a href='".$commenter_url."'>".
             $gravatar_code."</a>";
        } 
    }
}

It’s pretty straight forward so I’ve left it uncommented. If you need anything explained, just ask.