[solution][snipplet] function has_gravatar()

By.

min read

My profile

Share this:

Looking for an elegant method to see if a user has a gravatar or not ..

I stumbled upon this url: http://codex.wordpress.org/Using_Gravatars#Checking_for_the_Existence_of_a_Gravatar
> [quote:5c0742c973]The trick to do this is to specify “404” as the default. In this case, the gravatar service will return a 404 error if no gravatar exists, instead of returning some default image. A real image will get a 200 code. It is best to check for 200, as some other errors might be returned as well, for other cases. [/quote:5c0742c973]

[code:1:5c0742c973]
function validate_gravatar($email) {
// Craft a potential url and test its headers
$hash = md5($email);
$uri = ‘http://www.gravatar.com/avatar/’ . $hash . ‘?d=404’;
$headers = @get_headers($uri);
if (!preg_match(“|200|”, $headers[0])) {
$has_valid_avatar = FALSE;
} else {
$has_valid_avatar = TRUE;
}
return $has_valid_avatar;
}[/code:1:5c0742c973]

Works great, alltough I would have named the function has_gravatar($email); or user_has_gravatar($email);

So this is the code I use at http://www.ikzoekeensportpartner.nl :
Warning: you cannot simply copy paste this code below, but if you are a PHP coder, you’ll know what to do 🙂
[code:1:5c0742c973]
/**
* Checks if user has a gravatar or not
* @return boolean
*/
function has_valid_gravatar($email) {
// Craft a potential url and test its headers
$hash = md5($email);
$uri = ‘http://www.gravatar.com/avatar/’ . $hash . ‘?d=404’;
$headers = @ get_headers($uri);
if (!preg_match(“|200|”, $headers[0])) {
$has_valid_avatar = FALSE;
} else {
$has_valid_avatar = TRUE;
}
return $has_valid_avatar;
}

/**
* Returns gravatar OR default avatar url (if no gravatar found)
*/
function create_gravatar_url($email, $size) {
$rating = ‘R’;
global $default_gravatar;
if (validate :: email($email)) {
if (overall :: has_valid_gravatar($email)) {
return $url = “http://www.gravatar.com/avatar/” . md5($email) . “?r=” . $rating . “&default=” . $default_gravatar . “&size=” . $size;
}
}
return $default_gravatar;
}[/code:1:5c0742c973]

Share this:

Leave a Reply

Your email address will not be published. Required fields are marked *