StackTips
 2 minutes

How to validate user Gravatar for specific email id

By Editorial @stacktips, On Sep 17, 2023 Wordpress 2.27K Views

Gravatar is one of the most common service used widely on WordPress blogging platform. Gravatar is used for providing globally unique avatar for a specific email. During advance WordPress development, you may want to check if Gravatar is available for a users email, to display image or avatar from alternative source.

The following PHP snippet can be used to determine if Gravatar is available for specified email. It returns TRUE for valid gravatar otherwise it returns false.

function validateGravatar($email) {
	$hash = md5(strtolower(trim($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;
}
stacktips avtar

Editorial

StackTips provides programming tutorials, how-to guides and code snippets on different programming languages.